1

我有以下表格:

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);

author 包含其所有书籍,但每本书不包含其 BookBorrowers 属性。

author.Books.BookBorrowers.Count // that's zero but I have enities in those table for those book.
4

1 回答 1

1

您需要使用ThenInclude,例如:

var author = await _db.Authors
            .Include(a => a.Books)
            .ThenInclude(b => b.BookBorrowers) //Add this line
            .FirstOrDefaultAsync(a => a.Id == id);
于 2018-07-18T17:51:50.977 回答