EF Core 按列区分

2023-12-29

在 EF 6 中,如果我想通过不同的姓氏来选择用户,我可以这样做:

var users = _context.User
            .GroupBy(x => x.LastName)
            .Select(x => x.FirstOrDefault())
            .OrderBy(x => x.LastName)
            .Take(10)
            .ToList();

在 EF Core 3.1.6 中,这个完全相同的查询给出了以下异常:

System.InvalidOperationException: The LINQ expression '(GroupByShaperExpression:
KeySelector: (u.LastName), 
ElementSelector:(EntityShaperExpression: 
    EntityType: User
    ValueBufferExpression: 
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
)
)
    .FirstOrDefault()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

有没有什么方法可以使用该查询而不使用 AsEnumerable (或其他替代方案)将整个巨大的表加载到内存中?我下面使用的数据库是Microsoft SQL Server 2014,它可以处理这种查询。


EF Core 5 可能会支持此类查询(EF Core GitHub 存储库中肯定存在未解决的问题)。

EF Core 3.x 中的解决方法类似于如何使用 EF 3.1 在实体框架 GroupBy 中为每个组选择前 N 行 https://stackoverflow.com/questions/59456026/how-to-select-top-n-rows-for-each-group-in-a-entity-framework-groupby-with-ef-3- (1)使用子查询选择不同的键值,(2)然后将其与主查询结合限制运算符连接/关联(在这种情况下,Take(1)):

var users = _context.User.Select(x => x.LastName).Distinct() // (1)
    .SelectMany(key => _context.User.Where(x => x.LastName == key).Take(1)) // (2)
    // the rest is the same as the origonal
    .OrderBy(x => x.LastName)
    .Take(10)
    .ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

EF Core 按列区分 的相关文章

随机推荐