CRM Linq The ‘select’ and ‘orderBy’ calls may only reference a single common entity type

Posted on Posted in C#, MS Dynamics

When using Linq query in CRM you might come across error below..

“The ‘select’ and ‘orderBy’ calls may only reference a single common entity type”

Above error usually comes up if you are joing multiple entites  and returning a value back from any other entity than first.

Query:

var p = (from a in CrmRepository.accounts
join c in CrmRepository.contacts
on a.abc equals c.abc
select new { c.address1_city }).FirstOrDefault();

above query will throw the error

to fix this we have two options

1) Add ToList() to accounts i.e. from a in CrmRepository.accounts.ToList() but this will bring back all contacts first to store in memory

or

2) you change the query to below

var p = (from c in CrmRepository.contacts
join a in CrmRepository.accounts
on c.abc equals a.abc
select new { c.address1_city }).FirstOrDefault();