我有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.IEnumerable
1 [ComparingSite.Model.Prices.Price])' 方法,并且此方法无法转换为商店表达式。
所以:
如何获得产品包括其价格和旧价格,并在加入ef时过滤它们?
感谢。
答案 0 :(得分:0)
为什么不完全这样做,加入并过滤......如果表之间有关系? 如果我理解正确,这就是你需要的吗?
var prices = (from p in context.Products
join pr in context.Prices.Include("Prices.OldPrices") on p.ProductId equals pr.ProductId
join oldPr in context.OldPrices on pr.PriceId equals oldPr.PriceId
where p.ProductId > productId && pr.Enabled
&& oldPr.LastUpdate >= date
select pr).ToList(); // here you'll have prices with old prices
return new Product() { Prices = prices };