The entity cannot be constructed in a LINQ to Enti

2018-12-31 01:02发布

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?

13条回答
泪湿衣
2楼-- · 2018-12-31 01:36

You can use this and it should be working --> You must use toList before making the new list using select:

db.Products
    .where(x=>x.CategoryID == categoryID).ToList()
    .select(x=>new Product { Name = p.Name}).ToList(); 
查看更多
登录 后发表回答