2013-02-21 118 views
1

我有以下兩個表:,最大骨料選擇記錄使用LINQ to SQL

DocumentType 
    Id INT, 
    Name VARCHAR(100), 
    Active BIT, 
    CreatedBy INT 

Document 
    Id INT, 
    DocumentTypeId INT, 
    Version SMALLINT, 
    Text NTEXT 

我想選擇DocumentType及相關Document紀錄最大值爲Version。我想下面的查詢:

from t in Documents 
join tt in DocumentTypes on t.DocumentTypeId equals tt.Id 
where tt.CreatedBy == 10 
group t by t.DocumentTypeId into g 
//let v = new {Version = g.Max(t => t.Version), TypeId =g.Key} 
select new 
     { 
      Key = g.Key, 
      Version = g.Max(t=>t.Version), 
      Text = t.Text //ERROR AT t.Text 
     }; 

,但它給我一個錯誤在以下行:

Text = t.Text 

The name 't' does not exist in the current context 

我試圖g.Text也,但它並沒有幫助。請幫我解決這個問題。我在LinqPad上嘗試了這個。

回答

2

看來你需要檢索Document實體withing其對於Version屬性的最大值相同DocumentType。沒有必要按ntext列進行分組。

分組後你有文件組。剩下的唯一事情就是獲得每個組的最大Version值。我想此屬性遞減的順序排列組,並獲得的第一個值:

from t in Documents 
join tt in DocumentTypes on t.DocumentTypeId equals tt.Id 
where tt.CreatedBy == 10 
group t by t.DocumentTypeId into g 
select g.OrderByDescending(t => t.Version).FirstOrDefault(); 

你能預料的結果Document實體到匿名類型,如果你想要的。

0

t已經代替別的東西了。
嘗試這種方式

Version = g.Max(x=>t.Version), 
+0

人,這是好的,問題是在'文本= t.Text'到來。由於分組,它期望有一些聚合運算符,但它不能用於'NTEXT'類型的列。 – TheVillageIdiot 2013-02-21 05:36:14

1

嘗試

from t in Documents 
join tt in DocumentTypes on t.DocumentTypeId equals tt.Id 
where tt.CreatedBy == 10 
orderby t.Version descending 
group t by t.DocumentTypeId into g 

select new 
    { 
     Key  = g.Key, 
     Version = g.First().Version, 
     Text  = g.First().Text 
    };