c# - GroupBy() 之后展平 IQueryable<T> 时出错

标签 c# entity-framework linq

我试图从数据库中获取扁平对象,但出现错误。我想获取数据库中所有流派的两本书,代码如下:

IQueryable<Book> query = _context.Books
                                 .GroupBy(b => b.Genre)
                                 .SelectMany(bc => bc.Select(b => b).Take(2));

有人知道我在这里做错了什么吗?

我得到这个异常而不是结果:

The LINQ expression 'bc => bc .AsQueryable() .Select(b => b) .Take(2)' 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 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See go.microsoft.com/fwlink/?linkid=2101038 for more information.

我也尝试过类似的事情:

IQueryable<Book> query = _context.Genres.GroupJoin(
     _context.Books,
     g => g,
     b => b.Genre,
     (g, books) => new
     {
         Genre = g,
         BookCollection = books
     }
    ).SelectMany(bc => bc.BookCollection.Select(b => b)
    .Take(2)).Include(b => b.Author).Include(b => b.Rating)
             .Include(b => b.BookISBNs).Include(b => b.Reviews)
             .ThenInclude(r => r.User);

最佳答案

此尝试摆脱了分组依据,分组依据在数据库和 EF 查询转换中具有限制性。相反,我们将使用子查询。

var genres = _context.Books.Select(b => b.Genre).Distinct();
var books =
  from genre in genres
  from book in _context.Books.Where(b => b.Genre == genre).Take(2)
  select book;

var results = books.ToArrayAsync();

针对这种翻译:

SELECT c.*
FROM
  (SELECT DISTINCT Genre FROM Books) as a,
  (SELECT top 2 b.* FROM Books b WHERE b.Genre = a.Genre) as c

关于c# - GroupBy() 之后展平 IQueryable<T> 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66526675/

相关文章:

asp.net-mvc - 如何使用 C# ASP.net MVC 5 为特定模型创建单个迁移

c# - Entity Framework 7 与 ASP.NET 4.6

c# - 在 Entity Framework 中不同

c# - 消除循环并改用 Linq

C# Windows 窗体 - 如何根据背景颜色的深浅更改选项卡页标题文本颜色?

c# - ASP .NET Core 路由到外部程序集中的 Controller

c# - Linq 不区分大小写的连接

c# - 将多个类列表合并为 1 个列表

c# - 增加 Win7 Aero 主题中 DateTimePicker Calender 的字体大小

c# - DomainUpDown(微调器)控件正在切断显示文本的底部像素