2016-08-13 27 views
0

我有這些表:組通過LINQ不顯示預期的結果

TestPackagejoint(id,testpackageid,jointid) 
Joint(id,endid) 

我創建基於jointid,idtestpackagejoint和關節之間的關節。

我想組基於endidtestpackageid,以及endid或示例性計數的值:

testpackageid  endid  count 
1      2   3 
4      2   1 
1      3   2 

所以我寫這篇文章的查詢

var q = (from i in _ctx.TestPackageJoints 
       where i.TestPackageId == Id 
       join joint1 in _ctx.Joints on i.JointId equals joint1.Id 
       group new {joint1.EndId,i.TestPackageId} by new { i, joint1} 
       into g1 
       select new 
       { 
        testpackid = g1.Key.i.TestPackageId, 
        Count = g1.Count(), 
        endid = g1.Key.joint1.EndId 
       }).ToList(); 

但結果:

enter image description here

回答

2

你必須明白想得到什麼。你想得到testpackid和endid,所以對它們進行分組是正確的。你也想通過testpackid和endid進行分組,爲什麼你在這裏按新的{i,...}進行分組。

嘗試

group new {joint1.EndId,i.TestPackageId} by new {joint1.EndId,i.TestPackageId} 

或者

join ... 
let item = new {joint1.EndId,i.TestPackageId} 
group item by item 
2

您的查詢應該是:

var query = 
    from tpj in _ctx.TestPackageJoints 
    join j in _ctx.Joints on tpj.JointId equals j.Id 
    where tpj.TestPackageId == id 
    group 1 by new { tpj.TestPackageId, j.EndId } into g 
    select new 
    { 
     g.Key.TestPackageId, 
     g.Key.EndId, 
     Count = g.Count(), 
    }; 

group by子句形式group [object] by [key]。您包含一個TestPackageJoint對象作爲可能未定義相等性的關鍵字的一部分,因此它會爲每個配對生成一個組。