我有一个自定义工作流活动,它在删除作为父子关系中的子实体的实体时执行。
删除父实体时,会出现数据库错误。
我尝试在运行工作流之前检查父实体不为空,但删除子实体时它不为空;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 关系。