Click here to Skip to main content
15,900,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to get part of column 'code' and another column 'resnum' from my model named 'tabl' into a list of type 'tabl'. So I did this :

List<tabl> lsttablmaster = null;

lsttablmaster = Context.tabls.Select(r => new tabl { code = r.code.Remove(r.code.Length - 1), resnum = r.resnum }).ToList();


The above results in an Error :
"The entity or complex type cannot be constructed in a LINQ to Entities query"

If AsEnumerable() is added :
lsttablmaster = Context.tabls.AsEnumerable().Select(r => new tabl { code = r.code.Remove(r.code.Length - 1), resnum = r.resnum }).ToList();


No Error.

Here Im concerned, after reading online that if AsEnumerable() is used entire table is pulled into memory before applying the condition. Hence I want to ask what is the right way to go about this.

In what way the AsEnumerable() changes the scenario. Please suggest or point to right direction to read more. Thanks in advance.

What I have tried:

Though several links on Google points to the same error :

The entity or complex type  cannot be constructed in a LINQ to Entities query

nothing seemed more understandable to a newbie like me or I have not come across any such link.
Posted
Updated 31-Jan-19 18:59pm
v5

1 solution

That has something to do with the concepts of referred and deferred execution in LINQ.

Context.tabls.Select(r => new tabl { code = r.code.Remove(r.code.Length - 1), resnum = r.resnum })

This part would return a IQueryable<t> which executes only at the point when you call ToList() or iterate over the IQUeryable result for example with a foreach loop. In this case you can not map the entity to your modell. EF restricts that... I don't know why. Maybe to prevent updating / modifying entities while the result is not fully queried or fetched.

By using AsEnumerable() the query gets executed immediately and the result is stored in the memory.
After that it is possible to map the entities to your model / class / object as the full query result is already in the memory.

It might help you to get a little inside into the referred and deferred execution in LINQ / Entity Framework.

Kind regards.
 
Share this answer
 
Comments
Priya-Kiko 1-Feb-19 0:58am    
Thank you for your time and detailed explanation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900