我有一个图书数据库,其中包含作者的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}
我只是不知道如何遍历Authors列表中的Authors。类似于以下内容:
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
答案 0 :(得分:0)
您可以使用SelectMany:
var test = _context.Book.Include(x => x.Authors).ThenInclude(x => x.Quotes)
.SelectMany(x => x.Authors).Where(x => x.AuthorId == id);
答案 1 :(得分:0)
我认为包含将被忽略,因为从documentation开始,查询的结果类型与您启动时的dbset类型不同:
如果您更改查询以使其不再返回的实例, 查询开始的实体类型,则包含运算符为 忽略。
我假设bool
和Books
之间的关系是多对多的,如果是这种情况,那么我将按照以下方式进行查询:
Authors