debugcsharpCritical
The entity cannot be constructed in a LINQ to Entities query
Viewed 0 times
linqtheentityconstructedcannotqueryentities
Problem
There is an entity type called
I have written this query
The code below throws the following error :
"The entity or complex type Shop.Product cannot be constructed in a
LINQ to Entities query"
But when I use
How can I preform a custom select section?
Product that is generated by entity framework.I have written this query
public IQueryable 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?
Solution
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.
public class ProductDTO
{
public string Name { get; set; }
// Other field you may need from the Product entity
}And your method will return a List of DTO's.
public List GetProducts(int categoryID)
{
return (from p in db.Products
where p.CategoryID == categoryID
select new ProductDTO { Name = p.Name }).ToList();
}Code Snippets
public class ProductDTO
{
public string Name { get; set; }
// Other field you may need from the Product entity
}public List<ProductDTO> GetProducts(int categoryID)
{
return (from p in db.Products
where p.CategoryID == categoryID
select new ProductDTO { Name = p.Name }).ToList();
}Context
Stack Overflow Q#5325797, score: 435
Revisions (0)
No revisions yet.