There is an entity type called product that is generated by entity framework. I have writen this query
public IQueryable<Product> GetProducts(int categoryID)
{
return from p in db.Products
where p.CategoryID== categoryID
select new Product { Name = p.Name};
}
The code below throws the following error :
"The entity or complex type Shop.Product cannot be constructed in a LINQ to Entities query"
var products = productRepository.GetProducts(1).Tolist();
But when I use select p
instead of select new Product { Name = p.Name};
it works correctly.
How can I preform a custom select section?
You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an anonymous type or onto a DTO:
And your method will return a List of DTO's.
if you are Executing
Linq to Entity
you can't use theClassType
withnew
in theselect
closure of queryonly anonymous types are allowed (new without type)
take look at this snippet of my project
of you added the
new keyword
in Select closure even on thecomplex properties
you will got this errorbecause it will transformed to sql statement and executed on SqlServer
so when can I use
new with types
onselect
closure?you can use it if you you are dealing with
LINQ to Object (in memory collection)
after I executed
ToList
on query it becamein memory collection
so we can usenew ClassTypes
in selectIn response to the other question which was marked as duplicate (see here) I figured out a quick and easy solution based on the answer of Soren:
Note: This solution only works if you have a navigation property (foreign key) on the Task class (here called 'Incident'). If you don't have that, you can just use one of the other posted solutions with "AsQueryable()".
only add AsEnumerable() :
In many cases, the transformation is not needed. Think for the reason you want the strongly type List, and evaluate if you just want the data, for example, in a web service or for displaying it. It does not matter the type. You just need to know how to read it and check that is identical to the properties defined in the anonymous type that you defined. That is the optimun scenario, cause something you don't need all the fields of an entity, and that's the reason anonymous type exists.
A simple way is doing this:
Another simple way :)