gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:20:16 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com