【问题标题】:IOrganisationService.Retrieve Record does not existIOrganisationService.Retrieve 记录不存在
【发布时间】:2016-10-10 08:45:23
【问题描述】:

我编写了代码来检查 CRM 中的记录是否存在。问题是 IOrganisationService.Retrieve 在找不到记录时返回错误而不是 null。我希望找不到多条记录,并且我不想使用 try catch 然后使用 catch 中的错误。

using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, credentials, null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                //Get record

                var record = service.Retrieve(entryId, guid, new ColumnSet(true)); //switch to var if no work
                //Check if record is not null/empty
                recordExists = !String.IsNullOrWhiteSpace(record.Id.ToString()); //<- does the record exist
            }

建议?

【问题讨论】:

  • 为什么不想使用 try/catch?请参阅我的答案寻求帮助。

标签: c# dynamics-crm dynamics-crm-2013


【解决方案1】:

方法Retrieve 假定系统中确实存在具有给定ID 的记录。一般来说,它只在两种情况下失败:

  1. 记录已被其他用户或进程删除。
  2. 用户没有足够的读取权限。

当您需要查询可能不存在的数据或查询可以产生零、一条或多条记录时,请使用QueryExpression 查询;您可以使用RetrieveMultiple 方法发出这些查询。如果您愿意,您还可以使用 LINQ for CRM,它基本上封装了 QueryExpression 功能。

【讨论】:

    【解决方案2】:

    使用RetrieveMultiple 检索具有您感兴趣的 ID 的用户:

    // Create and cache the plugin context
    this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    this.service = serviceFactory.CreateOrganizationService(this.context.UserId);
    
    // Retrieve users with certain ID
    Guid userId = Guid.NewGuid();
    var query = new QueryExpression("systemuser");
    query.Criteria.AddCondition(new ConditionExpression("systemuserid", ConditionOperator.Equal, userId));
    
    EntityCollection users;
    try
    {
        users = this.service.RetrieveMultiple(query);
    }
    catch (FaultException<OrganizationServiceFault> faultException)
    {
        throw new InvalidPluginExecutionException($"Failed to retrieve system users that have an ID of '{userId}'", faultException);
    }
    
    if (users.Entities.Length == 0) // (or !users.Entities.Any() using Linq)
    {
        // Do something
    }
    

    【讨论】:

    • 代码有效,也许我的解释有点糟糕。如果没有找到结果,Retrieve 方法会出错;我想知道哪些 CRM 记录不存在,而不必使用 catch 说记录不存在。
    • 我认为使用Retrieve 方法是不可能的。如果记录不存在,CRM 服务将抛出 FaultException&lt;OrganizationServiceFault&gt; 类型的异常。但是,您可以使用RetrieveMultiple 检索具有您感兴趣的 ID 的记录列表 - 如果长度为 0,则不会引发异常。我已经更新了我的答案。
    • Retrieve 方法应该返回指定的记录,并且对它的调用只会在极少数情况下失败。因此,错误处理最好尽可能在最高级别进行。
    • @Phil 感谢您的帮助,您的解决方案对我有用。
    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 2014-04-04
    • 1970-01-01
    • 2017-09-11
    相关资源
    最近更新 更多