我已经制作了代码来检查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
}
建议?
答案 0 :(得分:3)
方法Retrieve
假设具有给定ID的记录实际存在于系统中。通常,它仅在两种情况下失败:
当您需要查询可能不存在的数据或查询可以产生零个,一个或多个记录时,请使用QueryExpression
个查询;您可以使用RetrieveMultiple
方法发出这些查询。如果您愿意,还可以使用LINQ for CRM,它基本上包含QueryExpression
功能。
答案 1 :(得分:1)
使用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
}