实体不能在LINQ to Entities查询中构建 [英] The entity cannot be constructed in a LINQ to Entities query

查看:175
本文介绍了实体不能在LINQ to Entities查询中构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个实体类型称为产品,由实体框架生成。
我已经写这个查询

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 :


实体或复杂类型Shop.Product不能在
LINQ to Entities查询中构造

"The entity or complex type Shop.Product cannot be constructed in a LINQ to Entities query"



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

但是当我使用选择p 而不是选择新产品{Name = p.Name}; 它可以正常工作。

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?

推荐答案

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

You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an annonymous type or onto a DTO:

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

而您的方法将返回DTO列表。

And your method will return a List of DTO's.

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

这篇关于实体不能在LINQ to Entities查询中构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆