从Dynamics 365 Plugin的相关记录中获取并使用Reference



我正在尝试编写一个简单的插件,触发更新的子记录,并计算从所有子记录到父的钱字段。

我已经尝试了一切,并设法让它工作时,从随机字段触发的帐户,但不是其他方式。

我得到的错误如下,即使所有字段都100%正确拼写并且不为空。完整的执行代码如下:

Exception Message: The given key was not present in the dictionary.
ErrorCode: -2147220956
HexErrorCode: 0x80040224
using System;
using System.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
namespace MyPlugin
{
public class SumRelatedProducts : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.Depth > 1)
{
return;
}
// Obtain the product from the input parameters.
Entity product = (Entity)context.InputParameters["Target"];

// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
// Retrieve the related entity
EntityReference relatedEntityRef = (EntityReference)product.Attributes["sen_accountid"];
Entity account = service.Retrieve(relatedEntityRef.LogicalName, relatedEntityRef.Id, new ColumnSet(true));
// Create a new organization service context.
var orgContext = new OrganizationServiceContext(service);
// Sum up the related products using an arrow function.
decimal sum = 0m;
var relatedProductEntities = orgContext.CreateQuery("sen_productmatrix")
.Where(a => ((EntityReference)a["sen_accountid"]).Id == relatedEntityRef.Id)
.ToList();
sum = relatedProductEntities.Sum(productEntity => ((Money)productEntity["sen_rev"]).Value);
// Update the sum on the account entity.
account["sen_sum"] = new Money(sum);
service.Update(account);
}
}
}

查找字段的逻辑和模式名称带有记录的子网格的可视化表示

我试过添加所有类型的验证,在下面的情况下,它抛出一个异常,这更令人困惑,因为显然字段存在,而不是空的,记录被保存。

if (product.Attributes.ContainsKey("sen_accountid"))
{
// Retrieve the related record
EntityReference acc = (EntityReference)product.Attributes["sen_accountid"];
Entity retrievedRecord = service.Retrieve("account", acc.Id, new ColumnSet(true));
(...)

您没有共享堆栈跟踪,但我猜错误发生在这一行:

EntityReference relatedEntityRef = (EntityReference)product.Attributes["sen_accountid"];

在处理update消息的插件管道中,实体作为"Target"在IPluginExecutionContext.InputParameters集合中只保存已修改的属性。处理更新所需的其他属性必须从实体前(或后)图像派生。

为您的插件步骤持有属性sen_accountid注册一个实体图像。

在您的插件中,您可以使用以下代码获取相关帐户记录的ID:

EntityReference relatedEntityRef = context.PreEntityImages
.First()
.Value
.GetAttributeValue<EntityReference>("sen_accountid");

相关内容

最新更新