asp.net - 复杂的 LINQ 查询 - 多表关系
问题描述
我有一个书籍数据库,其中包含作者的 ICollection。我想使用 LINQ 根据 AuthorId 返回作者对象。
Book db
int BookId
string Name { get; set; }
public ICollection<Author> Authors { get; set; }
Author db
int AuthorId
string Name
ICollection<Quote> Quotes { get; set; }
ICollection<Penname> Pennames { get; set; } - Edit: Added for clarity
我努力了:
var test = _context.Book.Include(x => x.Authors).Include("Authors.Quotes")
.Select(y => y.Authors)
这给了我:
EntityQueryable<ICollection<Authors>>
[0] {HashSet<Author>} [0]{Author} [1]{Author} [3]{Author}
[1] {HashSet<Author>} [0]{Author} [1]{Author}
[2] {HashSet<Author>} [0]{Author} [1]{Author}
我只是不知道如何迭代作者列表中的作者。如下所示:
var id = 2
var test = _context.Book.Include(x => x.Authors).Include("Authors.Quotes")
.Select(y => y.Authors.Select(x => x.Author).Where(x => x.AuthorId == id))
如果我进行重大更新,我可能会使用弹性...
更新@Marko Papic:
谢谢。奇怪的是,如果我使用下面的内容来获取作者的书籍列表,我会得到我所期望的填充的引号和笔名列表
var test = _context.Book.Include(x => x.Authors)
.ThenInclude(x => x.Quotes)
.Include(x => x.Authors)
.ThenInclude(x => x.Pennames)
但是,如果我使用 SelectMany,那么引号和笔名最终为空
var test = _context.Book.Include(x => x.Authors)
.ThenInclude(x => x.Quotes)
.Include(x => x.Authors)
.ThenInclude(x => x.Pennames)
.SelectMany(x => x.Authors).Where(x => x.AuthorId == id);
Author myauthor
int AuthorId = 2
string Name = "Bob"
ICollection<Quote> Quotes = null
ICollection<Penname> Pennames = null
解决方案
您可以使用SelectMany:
var test = _context.Book.Include(x => x.Authors).ThenInclude(x => x.Quotes)
.SelectMany(x => x.Authors).Where(x => x.AuthorId == id);
推荐阅读
- google-analytics - 事件跟踪之前的页面浏览量
- java - 斜线的SpringBoot路径变量问题
- android - React Native - 在包'android'(:app:processDebugResources)中找不到属性'appComponentFactory'的资源标识符
- if-statement - 在 csh if 语句中给出错误为“如果:格式错误的数字”。
- c# - 如何在 C# 中引用 UnitTesting DataSource 中的对象定义?
- amazon-web-services - 如何在 AWS 中使用 boto3 删除 Rds 实例和 Rds 集群
- pine-script - 激活后如何停止警报条件
- angular - router-outlet 正在附加而不是替换 IE 11
- c# - .Net 核心微服务事件代理使用 Solace
- php - 如何在 foreach 循环中使用 if 语句?