使用LINQ to SQL检索嵌套集合

时间:2014-06-21 22:57:39

标签: c# sql linq

我试图找回TransferIds列表,为每次转移一个ChargeIds列表,并为每个转发列表提供一个ReferralMatches

这是我所拥有的

(from c in Commissions
where c.TransferStatus == "Paid"
where c.AdminHasReleased == false
join r in ReferralMatches on c.ReferralMatchId equals r.ReferralMatchId
group c by new { c.TransferId } into grp
select new { 
   TransferId = grp.Key.TransferId,
   Charges = from c in grp
             group c by c.ChargeId into grp2
             select new { 
                ChargeId = grp2.Key, 
                Referrals = grp2 }
})

这很有效,非常接近。它拉回了看起来像这样的东西: enter image description here

这看起来像属于TransferId的费用,但我需要的是属于属于transferId的费用的ReferralMatches。我已经尝试过另一个选择进入' r'但遇到了错误。

我认为LINQ人员可以从这篇文章中收集他们需要的东西,但如果需要更多信息,请告诉我。谢谢。

编辑,添加表格样本

这两个扩展表是我必须使用的。它可能没有用,但请记住,ReferralMatch表也有ChargeId。一个chargeId可以涵盖多个ReferralMatches,但一旦资金可用,就会发生银行转账......当发生这种情况时,会在佣金表中创建记录。

所以我正在寻找的是TransferIds列表,foreach id是chargeIds列表,foreach chargeId是一个ReferralMatches列表...... ReferralMatches的最里面的列表将是该表的完整记录。

enter image description here

编辑,更多尝试

这是我的最新尝试

from c in Commissions
where c.TransferStatus == "paid"
group c by c.TransferId into transferGroup
select new {
    TransferId = transferGroup.Key,
    Charges = from c in transferGroup
              join r in ReferralMatches on c.ReferralMatchId equals r.ReferralMatchId
              group c by c.ChargeId into chargeGroup
              select new {
                ChargeId = chargeGroup.Key,
                Referrals = from r in chargeGroup
                            select new {
                                Referral = r
                            }
              }
}

这就是这样的: enter image description here

但除非我读错了,否则最里面的项目仍然是佣金表,这是没有意义的。我需要那个有[任何]

的ChargeId的ReferralMatches

1 个答案:

答案 0 :(得分:1)

您可能需要将表达式分离为两个并在第一个表达式中引用引用,然后按如下方式对第二个表达式进行分组:

        var commissionAndReferrals = 
            from c in Commissions
            where c.TransferStatus == "Paid"
            where c.AdminHasReleased == false
            join r in ReferralMatches on c.ReferralMatchId equals r.ReferralMatchId
            select new { Commisson = c, Referral = r };

        var result =
            from cAndR in commissionAndReferrals
            group cAndR by cAndR.Commisson.TransferId into transferGroup
            select new
            {
                TransferId = transferGroup.Key,
                Charges = from c in transferGroup
                          group c by c.Commisson.ChargeId into chargeGroup
                          select new
                          {
                              ChargeId = chargeGroup.Key,
                              Referrals = chargeGroup.Select(x => x.Referral)
                          }
            };