【发布时间】:2016-06-21 23:06:22
【问题描述】:
我有这个实体:
产品
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
价格表
public class PriceList
{
public int Id { get; set; }
public string Name { get;set; }
}
价格表产品
public class PriceListProduct
{
public int Id { get; set; }
public int PriceListId { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
问题是,如何使用 LINQ 获取价目表中没有的产品?
我的第一个想法是使用 Contains,但是产品列表可能大于 100000,如果将 Contains 翻译为 WHERE NOT IN 子句之类的查询,SQL 有大约 2000 个参数的限制,所以除了性能之外,我认为这不是最好的方法。
还有其他方法吗?我应该使用原始查询吗?
更新 #1
我正在尝试按照@Indregaard 的回答来理解 GroupJoin。到目前为止,我有这个。
var productsWithNoPrice = db.Product()
.GroupJoin(db.PriceListProduct().Where(plp => plp.PriceListId == 2)
.Select(plp => plp.Product),
p => p.Id,
plp => plp.Id,
(p, product) => new { p.Id, Product = product })
.Where(p => !p.Product.Any())
.Select(p => p.Product);
带滤镜
.Where(plp => plp.PriceListId == 2)
我正在从 ID 为 2 的价目表中过滤产品。我认为这很接近,但 SQL 生成的查询返回的行数对应于价目表中不存在的产品数,但每一列都是空。
基本上我需要的是这样的查询
select * from Product p
left join PriceListProduct plp on plp.ProductId = p.Id and plp.PriceListId = 2
where plp.Id is null
【问题讨论】:
-
“不在价目表中”是什么意思?即不在表格中,或不在某个具体列表中?
-
不在表中。例如,如果有 4 个产品(P1、P2、P3、P4)并且我有一个包含 P1 和 P3 的价目表,我怎样才能获得产品 P2 和 P4。
标签: asp.net-mvc entity-framework linq ef-code-first linq-to-entities