实体框架核心-与多对多关系的问题

时间:2020-08-30 16:04:02

标签: entity-framework-core

我的Get方法有问题。在我的BookRepository中,我有以下方法:

public Book GetBook(int id)
{
    return _context.Books
                   .Include(a => a.BookAuthors)
                   .Single(b => b.Id == id);
}

这是我的3个班级:

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual ICollection<BookAuthor> BookAuthors { get; set; }
    public string PublishingHouse { get; set; }
    public int NumberOfPages { get; set; }
    public int ISBN { get; set; }
}

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string SecondName { get; set; }
    public string Nationality { get; set; }
    public virtual ICollection<BookAuthor> BookAuthors { get; set; }
}

public class BookAuthor
{
    public int BookId { get; set; }
    public Book Book { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}

我想在屏幕上显示详细信息书,但是当我执行方法GetBook时,我得到了一个奇怪的模型-Book,其中包括BookAuthors。 ..书!一遍又一遍...

enter image description here

编辑:AuthorId还可以,但是Author为null-为什么?

我不知道如何在视图中显示Authors?通过foreach?

1 个答案:

答案 0 :(得分:0)

您仅包括BookAuthor。您没有包括作者。

将您的GetBook更改为

public Book GetBook(int id)
{
    return _context.Books
                   .Include(a => a.BookAuthors)
                   .Include("BookAuthor.Author")
                   .Single(b => b.Id == id);
}