I've made code to check if a record in CRM exists. Problem is that the IOrganisationService.Retrieve returns an error instead of a null when no record is found. I expect multiple records not to be found and I do not want to have to use a try catch then use the error from the 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
}
Suggestions?
Use RetrieveMultiple
to retrieve users with the ID you're interested in:
// 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
}