2014-01-22 13 views
0

我有一個自定義工作流程活動,它在刪除父子關係中的子實體時執行。關於刪除工作流程和家長關係

當父實體被刪除時出現數據庫錯誤。

我已經嘗試在運行工作流之前檢查父實體是否爲空,但在刪除子項時它不爲null; CRM必須先刪除孩子。

我實施了自己的機會產品實體(稱爲商機線)。
當機會行被創建,更改或刪除時,執行同步自定義工作流活動。
該工作流程會在機會產品(原始實體)中創建一個隱藏的寫入,其收入等於所有機會線加在一起;這樣做是爲了讓系統計算收益。我嘗試直接更新est。收入字段,但在機會設置爲系統計算時出現問題。

/* Deletes all Opportunity Products for this Opportunity and adds a single write in product 
* with the amount equal to the sum of all Opportunity lines 
* If the current message is delete then do not include the current record in the calculation 
* */ 
private void UpdateOpportunity(WorkflowContext context) // WorkflowContext contains everything retrieved from the CodeActivityContext 
{ 
    if (context.TargetReference != null || context.Target.Contains("wl_revenue")) // this is a delete or revenue update (or new record) 
    {     
     var linq = context.Linq; 
     var service = context.Service; 
     var lineId = (context.Target != null) ? context.Target.Id : context.TargetReference.Id; // context contains Target and TargetReference, Target is an entity and TargetReference is an Entity Reference, one is always not null 
     var opp = linq.wl_opportunitylineSet 
      .Where(line => line.Id == lineId) 
      .Select(line => line.wl_Opportunity) 
      .FirstOrDefault(); 
     if (opp != null) 
     { 
      var oppId = opp.Id; 
      if (oppId != null) 
      { 
       var lineAmounts = from line in linq.wl_opportunitylineSet 
            where line.wl_Opportunity.Equals(oppId) 
            where line.Id != lineId // The current line cannot be retrieved as it is the record in the transaction 
            select line.wl_Revenue; 
       decimal revenue = (context.Target != null && context.Target.Contains("wl_revenue")) 
        ? context.Target.GetAttributeValue<Money>("wl_revenue").Value : 0; // add the amount for this line if it just changed or was created 
       foreach (var amount in lineAmounts) 
        revenue += (amount != null) ? amount.Value : 0; 
       var oppProducts = from line in linq.OpportunityProductSet 
            where line.OpportunityId.Equals(oppId) 
            select line.Id; 
       foreach (var line in oppProducts) // there should be 0 or 1 
        service.Delete(OpportunityProduct.EntityLogicalName, line); 
       service.Create(new OpportunityProduct 
       { 
        IsPriceOverridden = true, 
        IsProductOverridden = true, 
        ProductDescription = "Income", 
        OpportunityId = opp, 
        PricePerUnit = new Money(revenue), 
        Quantity = 1 
       }); 
      } 
     } 
    } 
} 

這適用於所有情況,除非家長機會本身被刪除。 這應該以另一種方式完成,還是有可能讓工作流程不執行,如果它被刪除的機會,作爲一個單獨的行的姿勢?

我必須有一個自定義的機會線,主要是因爲機會產品不能用於任何自定義的1:N關係。

回答

0

首先,嘗試檢查工作流的執行深度:

if(context.Depth > 1) 
    return; 

我想,如果工作流程是由機會缺失事件觸發,那麼您的工作流程深度應大於1

如果它不起作用,您可以在機會中創建一個檢查字段,說is_deleted(是/否,默認爲否),然後創建一個插件將此字段更新爲在機會預操作刪除中爲yes。之後,在您的工作流代碼中,如果機會的is_deleted爲是,那麼您應該檢索並檢查此字段,然後返回,無需更新收入。

關於Est。機會收入,如果你使用手動計算,而不是系統計算,我認爲它更好,更容易。您可以更新Est。直接在您的代碼中收入,並且不需要將機會產品(原始)實體的事情複雜化。