有一种名为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};它工作正常。

如何执行自定义选择节?


当前回答

只添加AsEnumerable():

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

其他回答

你必须在使用select创建新列表之前使用toList:

db.Products
    .where(x=>x.CategoryID == categoryID).ToList()
    .select(x=>new Product { Name = p.Name}).ToList(); 

我还发现了另一种可行的方法,你必须从你的Product类中构建一个派生类并使用它。例如:

public class PseudoProduct : Product { }

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

不确定这是否“被允许”,但这是可行的。

另一种简单的方法:)

public IQueryable<Product> GetProducts(int categoryID)
{
    var productList = db.Products
        .Where(p => p.CategoryID == categoryID)
        .Select(item => 
            new Product
            {
                Name = item.Name
            })
        .ToList()
        .AsQueryable(); // actually it's not useful after "ToList()" :D

    return productList;
}

为了回应另一个被标记为重复的问题(见这里),我根据Soren的答案想出了一个快速而简单的解决方案:

data.Tasks.AddRange(
    data.Task.AsEnumerable().Select(t => new Task{
        creator_id   = t.ID,
        start_date   = t.Incident.DateOpened,
        end_date     = t.Incident.DateCLosed,
        product_code = t.Incident.ProductCode
        // so on...
    })
);
data.SaveChanges();

注意: 这个解决方案只适用于Task类上有一个导航属性(外键)(这里称为“Incident”)。 如果你没有,你可以使用“AsQueryable()”其他发布的解决方案之一。

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