【问题标题】:How to filter tables while joining in ef?加入ef时如何过滤表?
【发布时间】: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.List1[ComparingSite.Model.Prices.Price] ToList[Price](System.Collections.Generic.IEnumerable1[ComparingSite.Model.Prices.Price])' 方法,并且该方法不能翻译成商店表达式。

所以:

如何在加入ef时获取一个产品包括它的价格和旧价格并过滤它们?

谢谢。

【问题讨论】:

  • 您需要在属性中使用 IEnumeable 而不是 List,并删除查询中的所有内部 ToList 调用(顺便说一下,Includes 在那里也没用)。

标签: c# entity-framework linq


【解决方案1】:

如果表之间有关系,为什么不完全这样做,加入和过滤? 如果我理解正确,这是您需要的吗?

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 };

【讨论】:

  • 一切正常,只是价格的旧价格即将失效。
  • Include() 参数对吗?我认为应该是 context.Prices.Include("OldPrices") 而不是 "Prices.OldPrices" ....
猜你喜欢
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 2021-05-28
  • 2012-02-20
  • 1970-01-01
相关资源
最近更新 更多