[英]DefaultIfEmpty in LINQ-to-SQL join causing duplicates
这是我的查询的摘录:
...
join p in dc.PODs on c.ID equals p.Consignment into pg
from pgg in pg.DefaultIfEmpty()
...
查询应该做的是获取与寄售相关的所有“POD”,将其存储为 IEnumerable object(这似乎有效),以便在查询从查询生成的主要 IEnumerable 时运行它。
问题是,我使用 DefaultIfEmpty 行得到重复的主行,这仅在一行有多个 POD 时发生 - 所以它为每个 POD 返回一行,这是不正确的。 如果我取出 pg.DefaultIfEmpty() 行,它似乎工作得更好一些,但我仍然想获得没有 POD 的行。
有什么想法吗?
只是想确认您的第二种情况,output 不会没有没有项目的二、四、五,因为它不是外连接吗? One 1 TextBox Three 3 Refridgerator 3 Bucket
我尝试的是对 dc.PODS 使用等效的 WHERE IN。 ....join appraisal in ef_appraisal on application.a_appraisalid equals appraisal.a_appraisalid
where
(from r in..
select r.r_applicationid).Contains(application.a_id) )
如果您有其他想法,请分享
如果我不同意您的意图,请原谅我,因为我在您的查询摘录中看不到您的数据的完整结构或您的初始from
或 final select
子句。 因此,我发布了我认为基于您的代码段和我构建的示例数据的解决方案。 让我知道我是否离开,我会纠正它。
如果您想要一个托运到 POD 的行列表,并且每个托运到 POD 在其自己的行上,您可以执行以下操作(请记住我from
和select
子句基于我的示例数据):
// select the consignment id & name (i made up) and each matching POD
var results = from c in consignments
join p in dc.PODs on c.ID equals p.Consignment into pg
from pgg in pg.DefaultIfEmpty()
select new { ID = c.ID, Name = c.Name, POD = pgg };
// This is just a SAMPLE display just for kicks and grins
foreach (var r in results)
{
Console.WriteLine(r.Name + " " + ((r.POD != null)
? (r.POD.Consignment + " " + r.POD.Description)
: "none"));
}
此查询输出如下内容:
One 1 TextBox
Two none
Three 3 Refridgerator
Three 3 Bucket
Four none
Five none
但是我不太确定我是否理解您的评论:
“问题是,我得到重复的主行”
我不确定您是否说您不想看到每行每次购买的一个寄售,其中IEnumerable
中的每个结果都是带有寄售和一系列 POD 的项目,您需要这样的查询:
// select the Consignment ID and Name (i made up), and list of PODs
// instead of the individual POD
var results = from c in consignments
join p in dc.PODs on c.ID equals p.Consignment into pg
select new { ID = c.ID, Name = c.Name, PODs = pg };
// This is just a SAMPLE display just for kicks and grins
foreach (var r in results)
{
Console.WriteLine(r.Name + " ");
if (r.PODs.Count() > 0)
{
foreach (var pod in r.PODs)
{
Console.WriteLine("\t" + pod.Consignment + " " + pod.Description);
}
}
else
{
Console.WriteLine("\tNone");
}
}
select 正在选择 POD 列表而不是单个匹配项,其输出如下:
One
1 TextBox
Two
None
Three
3 Refridgerator
3 Bucket
Four
None
Five
None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.