2016-12-05 88 views
-1

我为报价和报价产品创建了两个名为“Price”的新字段,并且我想在每次更新第一个时更新第二个字段。Crm插件更新失败

这里是我的代码:

protected void ExecutePostAccountUpdateContacts(LocalPluginContext localContext) 
{ 
if (localContext == null) 
{ 
    throw new ArgumentNullException("localContext"); 
} 
string oldPrice = ""; 
string newPrice = ""; 

IPluginExecutionContext context = localContext.PluginExecutionContext; 
IOrganizationService service = localContext.OrganizationService; 

var ServiceContext = new OrganizationServiceContext(service); 
ITracingService tracingService = localContext.TracingService; 

if (context.InputParameters.Contains("Target") && 
context.InputParameters["Target"] is Entity) 
{ 
    Entity entity = (Entity)context.InputParameters["Target"]; 

    Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; 

    // get the post entity image 
    Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; 

    if (preImageEntity.Attributes.Contains("Price")) 
    { 
     oldPrice = (string)preImageEntity.Attributes["Price"]; 
    } 

    if (postImageEntity.Attributes.Contains("Price")) 
    { 
     newPrice = (string)postImageEntity.Attributes["Price"]; 
    } 

    if (newPrice != oldPrice) 
    { 
     try 
     { 
      //Create query to get the related contacts 
      var res = from c in ServiceContext.CreateQuery("Products") 
         where c["parentQuoteid"].Equals(entity.Id) 
         select c; 

      foreach (var c in res) 
      { 
       Entity e = (Entity)c; 
       e["Price"] = newPrice; 

       ServiceContext.UpdateObject(e); 
      } 

      ServiceContext.SaveChanges(); 
     } 
     catch (FaultException ex) 
     { 
      throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex); 
     } 
    } 

} 
} 

回答

0

虽然你没有问一个问题,你的查询是不完全正确。所以我假设你的插件在productparentquoteid查询失败。

并非所有的linq运算符都实现了,并且将实体逻辑名作为参数传递给create query,所以不是Products,而是product。没有开箱即用的字段parentquoteid,您是否缺少自定义属性前缀?

var res = from c in ServiceContext.CreateQuery("product") 
      where c.GetAttributeValue<Guid>("new_parentquoteid") == entity.Id 
      select c;