2013-02-21 66 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 
    };