实体框架选择一列具有最大值的行

时间:2015-03-19 11:29:41

标签: sql entity-framework

我有大约20列的表格。我希望获得包含每个ID最大“版本”列的所有列的行。

ID      | Version | Other data
--------+---------+----------
1       | 1       | text1
1       | 2       | text2
1       | 3       | text3
2       | 1       | text1
3       | 1       | text1
3       | 2       | text2

我想要的是:

ID      | Version | Other data
--------+---------+----------
1       | 3       | text3
2       | 1       | text1
3       | 2       | text2

我知道如何在sql中实现它。我不知道如何在实体框架上实现这一点。特别是如果我有20列。

2 个答案:

答案 0 :(得分:1)

context.TableName
    .GroupBy(x=>x.ID)
    .Select(x=>new 
    {
        ID = x.Key, 
        row = x.Where(r=>r.Version == x.Max(m=>m.Version)).FirstOrDefault()})
    .Select(x=>new {x.ID, x.row.Version, x.row.OtherData});

答案 1 :(得分:0)

我创建了自己的版本,但速度很慢

context.TableName.GroupBy(group=> group.recipeID)
                        .SelectMany(
                            group=>
                                group.Where(
                                    r=> r.version == group.Max(x => x.version))
                                    .Select(r=> r));