温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - The entity cannot be constructed in a LINQ to Entities query
c# entity-framework

c# - 无法在LINQ to Entities查询中构造实体

发布于 2020-04-04 00:38:39

有一个称为产品的实体类型,是由 Entity framework 生成的。我已经写了这个查询

public IQueryable<Product> GetProducts(int categoryID)
{
    return from p in db.Products
           where p.CategoryID== categoryID
           select new Product { Name = p.Name};
}

下面的代码引发以下错误:

“无法在LINQ to Entities查询中构造实体或复杂类型Shop.Product”

var products = productRepository.GetProducts(1).Tolist();

但是当我使用select p代替select new Product { Name = p.Name};它可以正常工作。

如何执行自定义选择部分?

查看更多

提问者
Ghooti Farangi
被浏览
51
25.5k 2018-10-31 20:19

您不能(也应该不能)投影到映射的实体上。但是,您可以投影到匿名类型或DTO上

public class ProductDTO
{
    public string Name { get; set; }
    // Other field you may need from the Product entity
}

并且您的方法将返回DTO的列表。

public List<ProductDTO> GetProducts(int categoryID)
{
    return (from p in db.Products
            where p.CategoryID == categoryID
            select new ProductDTO { Name = p.Name }).ToList();
}