RetrieveMultiple 调用中的 RetrieveMultiple(导致无限循环)

RetrieveMultiple within a RetrieveMultiple call (causes infinite loop)

我正在编写 CRM 插件。它应该在销售订单实体的 "RetrieveMultiple" 消息上触发,在第 20 阶段(预操作)。

问题是我需要在那个非常预操作阶段的所有现有销售订单的列表(以便将该列表与远程订单列表进行比较并在需要时创建新订单)。

要获取所有订单的列表,最简单的方法是使用 service.retrieveMultiple(salesOrderQuery),其中 salesOrderQuery 是 salesorder 上的 QueryExpression。

这当然会导致 Dynamics 365 进程进入无限循环。

我的问题是:对于一个"RetrieveMultiple"的salesorder消息,如何"pre-retrieve"所有处于pre-operation阶段的salesorder,而不会造成无限循环?

我目前在想,也许我应该更改导致我的插件被执行的事件。我的目标是在用户加载 "orders" 页面时从远程系统获取所有新创建的订单。到目前为止我发现的唯一方法是在 "RetrieveMultiple" 消息上注册我的插件步骤。

但是如何获取所有现有订单呢?

到目前为止,我的插件如下所示:

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSPlugins
{
    public class RetrieveOrdersPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {

            var context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;

            // check if pre-operation
            if (context.Stage != 20)
                throw new InvalidPluginExecutionException("Must run as pre-operation stage 20");
            if (context.MessageName != "RetrieveMultiple")
                throw new InvalidPluginExecutionException("Registered for " + context.MessageName + " only RetrieveMultiple is supported");
            if (context.PrimaryEntityName != "salesorder")
                throw new InvalidPluginExecutionException("Registered for " + context.PrimaryEntityName + " entity and only salesorder is supported");

            var tracingService = serviceProvider.GetService(typeof(ITracingService)) as ITracingService;
            var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
            var service = serviceFactory.CreateOrganizationService(context.UserId) as IOrganizationService;

            tracingService.Trace("Plug-in RetrieveOrders executed");

            QueryExpression soQuery = new QueryExpression();
            soQuery.EntityName = "salesorder";
            soQuery.ColumnSet = new ColumnSet() { AllColumns = true };

            soQuery.Criteria = new FilterExpression();
            soQuery.Criteria.FilterOperator = LogicalOperator.And;

            // The following line causes an infinite loop...
            EntityCollection entities = service.RetrieveMultiple(soQuery);

        }
    }
}

基本上 RetrieveMultiple 消息将在 Adv 查找、视图、查找等所有地方调用,service.RetrieveMultiple 系统正在查询该特定实体的调用。

使用 Depth 属性 的上下文 avoid infinite loops

if (context.Depth > 1)
    return;