我有下表:
public class Author
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<Book> Books { get; set; } = new List<Book>();
}
public class Book
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
public ICollection<BookBorrower> BookBorrowers { get; set; } = new List<BookBorrower>();
}
public class BookBorrower
{
public int Id { get; set; }
public int BookId { get; set; }
public Book Book { get; set; }
public int BorrowerId { get; set; }
public Borrower Borrower { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool IsBookReturned { get; set; } = false;
}
首先,我有一对多和多对多的关系。 现在的问题是如何通过作者包括BookBorrower。
我有这些代码
var author = await _db.Authors
.Include(a => a.Books)
.FirstOrDefaultAsync(a => a.Id == id);
作者包含其所有书籍,但每本书都不包含其BookBorrowers属性。
author.Books.BookBorrowers.Count // that's zero but I have enities in those table for those book.
答案 0 :(得分:1)
您需要使用ThenInclude
,例如:
var author = await _db.Authors
.Include(a => a.Books)
.ThenInclude(b => b.BookBorrowers) //Add this line
.FirstOrDefaultAsync(a => a.Id == id);