2012-06-25 32 views
1

我想爲下面的查詢編寫等價的linq代碼。我在做構建Linq查詢時做錯了什麼

SELECT A.* 
FROM 
( 
    SELECT * FROM TableA 
    WHERE id = 100 
) a 
JOIN 
( 
    SELECT Name, MAX(AnotherId) AnotherId 
    FROM TableA 
    WHERE id = 100 
    GROUP BY Name 
) b 
on a.Name = b.Name and a.AnotherId = b.AnotherId 

這是LINQ

var Collection = from R in DbContext.TableA 
join G in (DbContext.TableA.Where(r => r.Id == 100).GroupBy(r => new { r.Name, r.AnotherId }).Select(g => new { Name = g.Name , AnotherId = g.Max(o => o.AnotherId) })) 
on new { R.Name, R.AnotherId } equals new { G.Name, G.AnotherId } 
where R.Id == 100 
select R; 

但我得到以下編譯錯誤,我不知道如何解決。任何想法

連接子句中的一個表達式的類型不正確。在「加入」的調用中,類型推斷失敗。

錯誤7'System.Linq.IGrouping'沒有包含'Name'的定義,也沒有找到接受類型'System.Linq.IGrouping'的第一個參數的擴展方法'Name'(你是否缺少一個使用指令或程序集引用?)

+0

switch .Select()和.GroupBy()部件 – Alex

回答

2

通過r.Name,r.AnotherId,你組的時候你只是想組由r.Name。

var Collection = from R in DbContext.TableA 
join G in (DbContext.TableA 
         .Where(r => r.Id == 100) 
         .GroupBy(r => r.Name) 
         .Select(g => new { Name = g.Key , AnotherId = g.Max(o => o.AnotherId) })) 
on new { R.Name, R.AnotherId } equals new { G.Name, G.AnotherId } 
where R.Id == 100 
select R; 

,並具有一切以流利的語法

var collection = DbContext.TableA 
          .Where(t1 => t1.Id == 100) 
          .Join(DbContext.TableA 
           .Where(t2 => t2.Id == 100) 
           .GroupBy(t2 => t2.Name) 
           .Select(group => new{Name = group.Key, 
                 AnotherId = group.Max(e => e.AnotherId)}) 
           ), 
           t1 => new{t1.Name, t1.AnotherId} , 
           t2 => new{t2.Name, t2.AnotherId}, 
           (t1, t2) => t1); 
1

llHi需要以下語法,注意到除了「重點」

var Collection = from R in DbContext.TableA 
join G in (DbContext.TableA.Where(r => r.Id == 100) 
      .GroupBy(r => new { r.Name, r.AnotherId }) 
      .Select(g => new { Name = g.Key.Name , AnotherId = g.Max(o => o.AnotherId) })) 
on new { R.Name, R.AnotherId } equals new { G.Name, G.AnotherId } 
where R.Id == 100 
select R; 
1

我會建議使用的查詢語法您的查詢的所有部分。通過這樣做,您的linq查詢將具有與您的原始sql查詢更類似的結構。它應該是這樣的:

var query = 
    from a in 
    (from x in DbContext.TableA 
    where x.ID == 100 
    select x) 
    join b in 
    (from x in DbContext.TableA 
    where x.ID == 100 
    group x by x.Name into x 
    select new 
    { 
     Name = x.Key, 
     AnotherId = x.Max(o => o.AnotherId), 
    }) 
    on new { a.Name, a.AnotherId } equals new { b.Name, b.AnotherId } 
    select a; 
0

SAJ和拉斐爾都找到好點:

.GroupBy(r => new { r.Name, r.AnotherId }) 
.Select(g => new { Name = g.Name , AnotherId = g.Max(o => o.AnotherId) })) 

組不具有名稱。每個組都有一個密鑰(並且該密鑰有一個名稱和另一個ID)。

由於您希望Max(AnotherId),您不希望在您的分組鍵中包含AnotherId(與它在原始查詢的GroupBy子句中不存在相同)。

.GroupBy(r => r.Name) //the Name is the Key 
.Select(g => new { Name = g.Key, AnotherId = g.Max(o => o.AnotherId) }))