【发布时间】:2015-09-16 17:04:06
【问题描述】:
我有 3 张桌子。具有这种关系的 Product、Price 和 OldPrice:
(1)Product-->(*)Prices
(1)Price-->(*)OldPrices
我有一个返回产品及其价格和旧价格的方法,但我想在加入时过滤其价格和旧价格。我已经编写了这些方法,但我给出了这些错误:
方法一:
var date = DateTime.Now.AddDays(-(days));
Product q = (from p in context.Products.Include("Prices.OldPrices").Include("Prices.ClassPartner.SectionPartner.Partner")
where p.ProductId > productId
select new Product
{
Prices = (from pr in p.Prices
where pr.Enable == true
select new Price { OldPrices = (from o in pr.OldPrices where o.LastUpdate >= date select new OldPrice { LastUpdate = o.LastUpdate, Cost = o.Cost }).ToList() }).ToList()
}).FirstOrDefault();
return q;
错误一:
实体或复杂类型 'ComparingSite.Infrastructure.Repository.Product' 不能 在 LINQ to Entities 查询中构造。
然后我制作了一个名为 ProductDTO 的 DTO 模型,如下所示:
public class ProductDTO
{
public List<Price> Prices { get; set; }
}
然后像这样改变方法:
方法二:
var date = DateTime.Now.AddDays(-(days));
ProductDTO q = (from p in context.Products.Include("Prices.OldPrices").Include("Prices.ClassPartner.SectionPartner.Partner")
where p.ProductId > productId
select new ProductDTO
{
Prices = (from pr in p.Prices
where pr.Enable == true
select new Price { OldPrices = (from o in pr.OldPrices where o.LastUpdate >= date select new OldPrice { LastUpdate = o.LastUpdate, Cost = o.Cost }).ToList() }).ToList()
}).FirstOrDefault();
return new Product {Prices=q.Prices };
错误二:
LINQ to Entities 无法识别该方法 'System.Collections.Generic.List
1[ComparingSite.Model.Prices.Price] ToList[Price](System.Collections.Generic.IEnumerable1[ComparingSite.Model.Prices.Price])' 方法,并且该方法不能翻译成商店表达式。
所以:
如何在加入ef时获取一个产品包括它的价格和旧价格并过滤它们?
谢谢。
【问题讨论】:
-
您需要在属性中使用 IEnumeable
而不是 List ,并删除查询中的所有内部 ToList 调用(顺便说一下,Includes 在那里也没用)。
标签: c# entity-framework linq