Groupby实体与另一个表连接

时间:2013-02-08 09:36:46

标签: c# linq entity-framework

我有这种情况,我找不到任何解决相关SO问题的解决方案:

  (from TD as tx 
   join P as px  on tx.field1= px.ID
   join Q as rp  on tx.field2 = rp.ID
   join L as lc  on tx.field3= lc.ID
    group by  tx.field1,
              tx.field2, 
              L.randomfield4,
              ....a bunch of fields from P,Q,L
   )as groupItem
   left outer join M on groupItem.field1=M.ID
   select new { */ Elements from groupItem and M /*}

我的Linq看起来如下:

from tx in TD 
join itemP in P on tx.field1 equals P.ID
join itemQ in Q on tx.field2 equals P.ID
join itemL in L on tx.field3 equals P.ID
 group new { tx.field1 ,tx.field2 ,L.randomfield4 } by new { **fields from tx,p,q,etc} into groupItem 
 join dM in M on ???? 

如果我尝试从groupItems中选择元素,我无法访问礼节(因为我没有选择任何东西)。

任何人都可以帮我解决这个问题吗?
还帮助我提出更好的名称:)

1 个答案:

答案 0 :(得分:2)

希望我能正确理解你的问题,但这是我的答案。我把查询分成了两个,所以如果你完全进入它,它很容易理解,只需将它们组合在一起。

基本上变量“groupedCollection”是你的第一个连接和你的分组,它基本上包括以下集合TD,P,Q和L.然后第二个变量“finalCollection”是你的左外连接,它可以提供你需要的结果。

var groupedCollection = from tx in TD
join itemP in P on tx.field1 equals itemP.ID
join itemQ in Q on tx.field2 equals itemQ.ID
join itemL in L on tx.field3 equals itemL.ID
group new
{   
    //Select the collections you want to group it by
    P,
    Q,
    L,
    TD
}
by new
{
    //Select fields you want to output group by here
    tx.field1,
    tx.field2,
    tx.field3,
    itemL.RandomField4
}
    into g
    select new
    {
        //Use ky to get your properties as they are already grouped by
        yourField1 = g.Key.field1,
        yourField2 = g.Key.field2,
        yourField3 = g.Key.field3,
        yourField4 = g.Key.RandomField4
    };

var finalCollection = from dM in M
    //This is your Left Outer Join
    join xx in groupedCollection on dM.ID equals xx.yourField1 into sr
    from w in sr.DefaultIfEmpty()
    //Until here
    select new
    {
        finalResultID = dM.ID,
        finalField1 = w.yourField1,
        finalField2 = w.yourField2,
        finalField3 = w.yourField3,
        finalField4 = w.yourField4
    };

对于更多LINQ的东西,这会给你一个想法 http://anyrest.wordpress.com/2010/09/27/linq-to-sql-essentials/