有一种名为Product的实体类型是由实体框架生成的。 我写了这个问题

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

下面的代码抛出以下错误:

实体或复杂类型的Shop。产品不能构造在 LINQ到实体查询"

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

但是当我使用select p而不是select new Product {Name = p.Name};它工作正常。

如何执行自定义选择节?


当前回答

如果你正在使用实体框架,那么尝试从DbContext中删除属性,它使用你的复杂模型作为实体 当映射多个模型到名为实体的视图模型时,我也有同样的问题

public DbSet<Entity> Entities { get; set; }

从DbContext中删除条目修复了我的错误。

其他回答

如果你正在使用实体框架,那么尝试从DbContext中删除属性,它使用你的复杂模型作为实体 当映射多个模型到名为实体的视图模型时,我也有同样的问题

public DbSet<Entity> Entities { get; set; }

从DbContext中删除条目修复了我的错误。

只添加AsEnumerable():

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

您不能(也不应该)将项目投射到映射实体上。但是,你可以投射到匿名类型或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();
}

你可以像下面这样添加AsEnumerable到你的集合:

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

您可以通过使用数据传输对象(DTO)来解决这个问题。

这有点像视图模型,你可以在视图模型中输入你需要的属性,你可以在控制器中手动映射它们,也可以使用第三方解决方案,如AutoMapper。

使用DTO,你可以:

使数据可序列化(Json) 摆脱循环引用 通过留下你不需要的属性来减少网络流量(viewmodelwise) 使用objectflattening

我今年在学校学过这个,这是一个非常有用的工具。