【问题标题】:EF Core: group by => InvalidOperationExceptionEF Core:分组方式 => InvalidOperationException
【发布时间】:2020-10-13 19:04:28
【问题描述】:

我正在从事某种教育项目(为我自己)来学习 EF Core -> 代码优先方法,我正在努力解决我的查询出了什么问题。 A 有两个简单的实体:文章和用户,我想对它们进行分组以获取对象列表,其中包含具有相关文章的所有用户的列表。

        {
            var authorRowModels =
                from articles in _myContext.Articles
                join authors in _myContext.Users on articles.Author.Id equals authors.Id
                group new { articles, authors } by authors into authorWithArticles
                select new 
                {
                    AuthorFirstName = authorWithArticles.Key.FirstName,
                    AuthorLastName = authorWithArticles.Key.LastName,
                    Articles = authorWithArticles.Select(x => x.articles)
                };

            return View(authorRowModels.AsEnumerable().Select(x => new AuthorRowModel
            {
                AuthorFirstName = x.AuthorFirstName,
                AuthorLastName = x.AuthorLastName,
                Articles = x.Articles.ToList()
            }));
        }

但我收到一个错误:

InvalidOperationException: LINQ 表达式 'DbSet .LeftJoin( outer: DbSet, inner: a => EF.Property(a, "AuthorId"), outerKeySelector: u0 => EF.Property(u0, "Id"), innerKeySelector: (o, i) => new TransparentIdentifier

( Outer = o, Inner = i )) .Join( outer: DbSet, inner: a => a.Inner.Id, outerKeySelector : u => u.Id, innerKeySelector: (a, u) => new TransparentIdentifier, User>( Outer = a, Inner = u )) .GroupBy( 来源: ti => ti.Inner , keySelector: ti => new {articles = ti.Outer.Outer, authors = ti.Inner })' 无法翻译。以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。有关详细信息,请参阅 https://go.microsoft.com/fwlink/?linkid=2101038。

我不知道 EF 不能翻译什么。另外,如果您有提示如何以更好的方式重写此查询,即使没有分组也很好:)

谢谢。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    在 EF LINQ 中使用 join 几乎总是错误的解决方案。

    使用导航属性,这可以简单地类似于:

     var authorRowModels = from a in _myContext.Users
                           where a.Articles.Any()
                           select new
                           {
                             a.FirstName,
                             a.LastName,
                             a.Articles
                           };
    

    【讨论】:

    • 感谢您的回答。它看起来确实像更优雅的解决方案(我什至不需要“where”子句,因为我想显示所有作者)。我没有想到,因为我的“用户”实体上没有“文章”属性,但这是一个简单的修复。但是,如果我想要(我不想要:))到使用加入/组的那个,我该怎么做?正如我所说,这是出于教育目的,我想了解它是如何工作的以及为什么它不能那样工作。
    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2020-12-01
    相关资源
    最近更新 更多