Posts with tag: QueryExpression

I think most people whom use the generated service context for Microsoft CRM quickly note that it does not use the full fledged entity framework and as such does not support all queries. One of these limitations that I usually hit on is that I cant use contains in a Lambda query.

Ie. This does not work and fails with this error: Invalid 'where' condition. An entity member is invoking an invalid property or method.

private List<Xrm.Account> GetAccountsFromOrgNoList(string[] orgNos)
{
    return serviceContext.Xrm.AccountSet
        .Where(x => orgNos.Contains(x.lgc_Organizationnumber))  // <-- contains is invalid
        .Select( x=> x)
        .ToList();
}

The work around for this is to use Query Expressions. Because they can do this, although not as nicely. The below code does the same as the above code with the added exception of actually working.

private List<Xrm.Account> GetAccountsFromOrgNoList(string[] orgNos)
{
    var qe = new QueryExpression(Xrm.Account.EntityLogicalName);
    qe.ColumnSet = new ColumnSet("accountid", "name", "cst_organizationnumber"); // can use new ColumnSet(true); if you just want all columns instead of specifying specif ones
    qe.Criteria.AddCondition("cst_organizationnumber", ConditionOperator.In, orgNos.Cast<Object>().ToArray());
    qe.Distinct = true;

    var results = serviceContext.Instance.RetrieveMultiple(qe).Entities
        .Select(x => x.ToEntity<Xrm.Account>())
        .ToList();

    return results;
}