Wednesday, August 17, 2016

Count total number of records – what is the issue

Count total number of records – what is the issue



How simple can that be to count total number of records – just use linq query using EntitySetobject like the one below
?
1
var contactCounter = new ServiceContext(_service).ContactSet.Select(item => item).Count();
and that’s it. But no – you will get an exception:
Invalid ‘count’ condition. An entity member is invoking an invalid property or method.

Why?

If we use var as variable type (rather than strongly typed) then Select linq statement will useIQueryable as a default output type. Simple trick is to declare variable type and use CreateQuerystatement when using OrganizationServiceContext

Solution

?
1
2
IEnumerable<Entity> contacts = new ServiceContext(_service).CreateQuery(Contact.EntityLogicalName).Select(item => item);
           var contactCountere = contacts.Count();

No comments:

Post a Comment