简体   繁体   English

LINQ 到 SQL 中的 DefaultIfEmpty() 连接导致重复

[英]DefaultIfEmpty() in LINQ to SQL join causing duplicates

Code:代码:

var cons = from c in dc.Consignments
join p in dc.PODs ON c.ID equals p.Consignment into pg
from p in pg.DefaultIfEmpty()
...(other joins)...
select new {
...
PODs = pg
...
}

Basically, I want one row to be selected for each Consignment, and I want to select the object 'PODs' which should be a collection of PODs.基本上,我想为每个寄售选择一行,我想 select object 'PODs' 这应该是 PODs 的集合。 This works, however I get an row for each POD there is - so if I have 3 POD's on a consignment, 3 rows will be returned for that consignment.这可行,但是我为每个 POD 得到一行 - 因此,如果我在一个货物上有 3 个 POD,则将为该货物返回 3 行。 Am I selecting the PODs incorrectly?我是否错误地选择了 POD? If I take away the DefaultIfEmpty(), it strangely works fine and doesn't cause duplicates.如果我拿走 DefaultIfEmpty(),它奇怪地工作正常并且不会导致重复。

You're using a second from clause, which is effectively flattening things - but then you're still using pg in your select .您正在使用第二个from子句,它有效地使事情变平 - 但是您仍然select中使用pg The point of DefaultIfEmpty() is if you want a left outer join, effectively - where you would expect one result per valid combination. DefaultIfEmpty()的要点是,如果你想要一个有效的左外连接 - 你会期望每个有效组合都有一个结果。

I suspect you just want:我怀疑你只是想要:

var cons = from c in dc.Consignments
join p in dc.PODs ON c.ID equals p.Consignment into pg
select new {
  ...
  PODs = pg
  ...
}

or maybe或者也许

var cons = from c in dc.Consignments
join p in dc.PODs ON c.ID equals p.Consignment into pg
select new {
  ...
  PODs = pg.DefaultIfEmpty()
  ...
}

... but the latter will give you a result with a single null entry in PODs when there weren't any PODs, which probably isn't what you were after. ...但是当没有任何 POD 时,后者会在PODs中为您提供一个 null 条目的结果,这可能不是您所追求的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM