Retrieve Dynamic Entities By Property in CRM 4.0

by Matt 30. July 2010 16:14

The building up of a QueryExpression in CRM 4.0 SDK is a bit different than it was in 3.0 because of the introduction of generics to .NET, and is no longer dependant on arrays like it was for CRM 3.0, which was built on .NEt 1.1.

In 3.0, you did something like the following:

query.Criteria.Conditions = new ConditionExpression[] { condition1, condition2 };

Essentially, you added each condition to a ConditionExpression array to your query criteria conditions.  Now, in CRM 4.0 with all of the goodness of generics, your code now looks like

filter.AddCondition(con1);
filter.AddCondition(con2);

Our PluginHelper project had a method that allowed the user to retrieve a Dynamic Entity based on the primary key, but I needed a way to retrieve Dynamic Entities based on other properties.

I modified the following method based on another I had previously written for the 3.0 SDK.  It requires an object that has inherited from ICrmService, and also the name of the entity, the property on the entity on which you are querying, and the value of that property.

public static IList<DynamicEntity> RetrieveDynamicEntitiesByProperty(
    ICrmService service, string Entity, string Column, string Value)
{
    ConditionExpression con = new ConditionExpression();
    con.AttributeName = Column;
    con.Operator = ConditionOperator.Equal;
    con.Values = new string[] { Value };

    FilterExpression filter = new FilterExpression();
    filter.FilterOperator = LogicalOperator.And;
    filter.AddCondition(con);

    QueryExpression query = new QueryExpression();
    query.EntityName = Entity;
    query.ColumnSet = new AllColumns();
    query.Criteria = filter;

    RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
    retrieve.Query = query;
    retrieve.ReturnDynamicEntities = true;
    RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);

    //I prefer Lists to BusinessEntityCollection objects
    IList<DynamicEntity> Entities = new List<DynamicEntity>();
    foreach (DynamicEntity de in retrieved.BusinessEntityCollection.BusinessEntities)
        Entities.Add(de);

    return Entities;
}

If you want to return only a single entity rather than a full list, you can change the return type to DynamicEntity and alter the end of that method as such:

if (retrieved.BusinessEntityCollection.BusinessEntities.Count == 0)
                return null;
DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0];
return entity;

This method has proven invaluable and is currently being used by about a dozen plugins since I wrote it a month ago.

Categories: .NET | C# | CRM