以下代码是在 Microsoft Dynamics CRM 插件中创建的。代码在 aproduct
Entity
更新后执行。product
Entity
在被调用中有一个自定义字段labourRate
。选择所有字段以传递给插件:
protected void ExecutePostProductUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
//Get the IOrganizationService
IOrganizationService service = localContext.OrganizationService;
//create the service context
var ServiceContext = new OrganizationServiceContext(service);
ITracingService tracingService = localContext.TracingService;
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];
// get the pre entity image
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;
Money price = new Money();
price = (Money)postImageEntity.Attributes["price"];
var products = from p in ServiceContext.CreateQuery("product")
select p;
foreach (var product in products)
{
Entity e = (Entity)product;
Money newPrice = new Money();
decimal labourRate = 1;
// get the preimage and postimage telephone1 value
if (preImageEntity.Attributes.Contains("new_labourrate"))
{
try
{
labourRate = (decimal)e["new_labourrate"];
}
catch
{
}
}
newPrice.Value = price.Value * labourRate;
e["price"] = newPrice;
ServiceContext.UpdateObject(e);
}
ServiceContext.SaveChanges();
}
}
上面的代码导致以下错误:
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault,
Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]:
Unexpected exception from plug-in (Execute): Plugins1.PostProductUpdate:
Microsoft.Xrm.Sdk.SaveChangesException: An error occured while processing this request.
Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220956</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
<Message>Unexpected exception from plug-in (Execute): Plugins1.PostProductUpdate:
Microsoft.Xrm.Sdk.SaveChangesException: An error occured while processing this request. </Message>
<Timestamp>2013-08-22T08:26:27.6655137Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText>
[Plugins1: Plugins1.PostProductUpdate]
[08445d1c-5e06-e311-b80b-3c4a92dbc855: PostProductUpdate]
</TraceText>
</OrganizationServiceFault>