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

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

问题描述:

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

I have an issue with my Get method. In my BookRepository I have this method:

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 时,我得到了一个奇怪的-model,其中是 Book ,其中包括BookAuthors ,其中包括... Book!一遍又一遍...

I want display details book on the screen, but when I executed method GetBook, I have get something weird -model where is a Book, which includes BookAuthors, which includes... Book! And again, and again...

AuthorId 可以,但是Author为null-为什么?

AuthorId is ok, but Author is null - why?

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

And I don't have any idea how I can display Authors in the view? By foreach?

您仅包含BookAuthor.您不包括作者.

You only included BookAuthor. You didn't include Author.

将您的GetBook更改为

Change your GetBook to

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