2016-12-05 85 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;