展平IQueryable< T>时发生错误在GroupBy()之后 [英] Error while flattening the IQueryable<T> after GroupBy()
问题描述
我正在尝试从数据库中获取扁平化的对象,但出现错误.我想获得数据库中所有流派的2本书籍,代码如下:
I am trying to get flattened object from the database, but I get an error. I want to get 2 books for all genres in the database, the code looks like this:
IQueryable<Book> query = _context.Books
.GroupBy(b => b.Genre)
.SelectMany(bc => bc.Select(b => b).Take(2));
有人知道我在这里做什么错吗?
Does anyone know what am I doing wrong in here?
我得到这个异常而不是结果:
I get this exception instead of a result :
LINQ表达式'
bc =>bc .AsQueryable().Select(b => b).Take(2)
'无法翻译.以一种可以翻译的形式重写查询,或者通过插入对"AsEnumerable","AsAsyncEnumerable","ToList"或"ToListAsync"的调用来显式切换到客户端评估.有关更多信息,请参见go.microsoft.com/fwlink/?linkid=2101038.
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.
我也尝试过类似的事情:
I tried also something like that :
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查询转换中是有限制的.取而代之的是,我们要去一个子查询.
This attempt moves away from group by, which is restrictive in the database and EF query translation. Instead, we're going for a subquery.
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
这篇关于展平IQueryable< T>时发生错误在GroupBy()之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!