C# – How to retrieve a single record on Microsoft CRM using c# if I don’t know the GUID

cdynamics-crm-2011

We have a vendor solution here where it uses Microsoft Dynamics CRM as base. The application includes this custom entity which has the following attributes (truncated to only show the relevant bits)

relationship entity (works like a list of values. like values for populating a dropdown list)

relationshipid (guid datatype. primary key)
description (string and sample values would include "staff" or "customer" or "visitor" and etc)

I want to retrieve a single record from the entity. something like:

select * from relationship where description like "staff%"

I know there's a Retrieve function but I need the guid to use that. I want to emulate the SQL above without having to possibly use QueryExpression. I want to get an object of type Entity instead of EntityCollection which is what a QueryExpression will give me.

thanks a lot 🙂

Best Answer

The SDK doesn't provide a method to return a single entity unless you have its Id. But you can write an extension method to help yourself out.

Here is what I use:

/// <summary>
/// Gets the first entity that matches the query expression.  Null is returned if none are found.
/// </summary>
/// <typeparam name="T">The Entity Type.</typeparam>
/// <param name="service">The service.</param>
/// <param name="qe">The query expression.</param>
/// <returns></returns>
public static T GetFirstOrDefault<T>(this IOrganizationService service, QueryExpression qe) where T : Entity
{
    qe.First();
    return service.RetrieveMultiple(qe).ToEntityList<T>().FirstOrDefault();
}


/// <summary>
/// Converts the entity collection into a list, casting each entity.
/// </summary>
/// <typeparam name="T">The type of Entity</typeparam>
/// <param name="col">The collection to convert</param>
/// <returns></returns>
public static List<T> ToEntityList<T>(this EntityCollection col) where T : Entity
{
    return col.Entities.Select(e => e.ToEntity<T>()).ToList();
}

The GetFirstOrDefault ensures that the QE is only going to retrieve one entity. The ToEntityList Casts each entity to the early bound type being returned.

So the call would look like:

var contact = service.GetFirstOrDefault<Contact>(qe);
Related Topic