I have a statement:
var items = from e in db.Elements
join a in db.LookUp
on e.ID equals a.ElementID
where e.Something == something
select new Element
{
ID = e.ID,
LookUpID = a.ID
// some other data get populated here as well
};
As you can see, all I need is a collection of Element objects with data from both tables – Elements and LookUp. This works fine. But then I need to know the number of elements selected:
int count = items.Count();
… this call throws System.NotSupportedException:
“The entity or complex type ‘Database.Element’ cannot be constructed in a LINQ to Entities query.”
How am I supposed to select values from multiple tables into one object in Entity Framework? Thanks for any help!
Your code doesn’t work at all. The part you think worked has never been executed. The first time you executed it was when you called
Count.As exception says you cannot construct mapped entity in projection. Projection can be made only to anonymous or non mapped types. Also it is not clear why you even need this. If your class is correctly mapped you should simply call:
If
LookupIDis mapped property of yourElementclass it will be filled. If it is not mapped property you will not be able to load it with single query toElement.