[英]Obtain and use Reference from a related record in Dynamics 365 Plugin
我正在嘗試編寫一個簡單的插件來觸發子記錄的更新,並計算所有子記錄到父記錄的貨幣字段。
我已經嘗試了所有方法,並設法在從帳戶中的隨機字段觸發時讓它工作,但不是另一種方式。
我得到的錯誤如下所示,即使所有字段都 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
消息的插件管道中, IPluginExecutionContext.InputParameters
集合中作為“目標”傳遞的實體僅包含已修改的屬性。 處理更新所需的其他屬性必須來自實體預(或后)圖像。
為您的插件步驟注冊實體圖像持有屬性sen_accountid
。
在您的插件中,您可以使用以下代碼獲取相關帳戶記錄的 ID:
EntityReference relatedEntityRef = context.PreEntityImages
.First()
.Value
.GetAttributeValue<EntityReference>("sen_accountid");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.