Search code examples
linqlinq-to-entitiesdynamics-crm-2011dynamics-crm-2013

CRM 2013 service, using linq dynamic queries on the endpoint


I have trouble using dynamic queries on the crm end-point. The funny thing is if i apply the same linq filter on an handmade array, the query executes correctly:

this is part of the code that is working:

 List<Account> per = new List<Account>();
 per.AsQueryable();
 per.Add(new Account { LogicalName = "account" });
 per.Add(new Account { LogicalName = "account" });
 per.Add(new Account { LogicalName = "account" });
 per.Add(new Account { LogicalName = "account" });
 per.Add(new Account { LogicalName = "account" });
 per[0]["name"] = "Fourth1";
 per[1]["name"] = "Fourth2";
 per[2]["name"] = "Fourth3e";
 per[3]["name"] = "Fourth4e";
 per[4]["name"] = "Fourth5";
 per[0]["address1_postalcode"] = "Fourth1";
 per[1]["address1_postalcode"] = "Fourth2";
 per[2]["address1_postalcode"] = "Fourth3e";
 per[3]["address1_postalcode"] = "Fourth4e";
 per[4]["address1_postalcode"] = "Fourth5";
 fields.Add("Attributes[\"name\"].ToString().Contains(@0)");
 List<object> paramObjects = new List<object>();

 var where = string.Join(" ", fields.ToArray());
 var toParam = keyPosition.ToArray();
 int queryz = per.AsQueryable().Where(where, toParam).ToList().Count;

Till here everything is fine, the filters are working and I'm able to basically do whatever i want. This is the part that gives me trouble:

var query_exists = service.CreateQuery("account");
List<Entity> ent = query_exists.ToList();
int c=  ent.AsQueryable().Where(where, toParam).ToList().Count;

Using the same parameters as top I was expecting the same query to work, but if I try to apply it to the service.CreateQuery() everything just fails with a generic the key was not present into the dictionary. Someone knows if there is any difference between the handmade array and the one that I'm converting from the endpoint?


Solution

  • hitting my head pretty hard on this i discovered that if one of this properties in the array contains a single null value the dynamic linq query fails badly. So if you want to use this approach you need to be sure that your array is complete and that all the fields have at least an empty string since if the field that you are looking for has a null the query will fail.