admin管理员组文章数量:1287966
I have a database of books. Books have a related genre. Two tables: Book
and Genre
.
How do I alter this:
var data = await _context.Genres.ToListAsync();
to return a count - along with the data - of how many books are in the database for each genre?
I have a database of books. Books have a related genre. Two tables: Book
and Genre
.
How do I alter this:
var data = await _context.Genres.ToListAsync();
to return a count - along with the data - of how many books are in the database for each genre?
Share Improve this question edited Feb 22 at 17:12 marc_s 755k184 gold badges1.4k silver badges1.5k bronze badges asked Feb 22 at 17:08 D.ManD.Man 3114 silver badges17 bronze badges 03 Answers
Reset to default 4This is an untested code:
var data = await _context.Books
.GroupBy(b => p.Genre)
.Select(g => new { name = g.Key.name, count = g.Count() })
.ToListAsync();
Since I did not work with C# and .NET for many years, it's possible that this code has typos. Let me know if that is the case.
You can return a subquery using an anonymous type (or a real type if you prefer) containing both Genre
and a count
var data = await _context.Genres
.Select(g => new {
Genre = g,
BookCount = g.Books.Count(),
})
.ToListAsync();
If your relationship is only available in the reverse direction (which is wrong anyway), then you can do
var data = await _context.Books
.GroupBy(b => b.Genre)
.Select(g => new {
Genre = g,
BookCount = g.Count(),
})
.ToListAsync();
This produced the results I needed: -
var data = await _context.Books.Include(i => i.Genre)
.GroupBy(b => b.Genre)
.Select(g => new { name = g.Key, id = g.Key.Id,
description = g.Key.Description,
count = g.Count() })
.ToListAsync();
本文标签: How do I return data with a per type count using EF Core in ASPNET MVC using CStack Overflow
版权声明:本文标题:How do I return data with a per type count using EF Core in ASP.NET MVC using C#? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741333225a2372887.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论