我的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
。 ..书!一遍又一遍...
编辑:AuthorId
还可以,但是Author为null-为什么?
我不知道如何在视图中显示Authors
?通过foreach?
答案 0 :(得分:0)
您仅包括BookAuthor。您没有包括作者。
将您的GetBook更改为
public Book GetBook(int id)
{
return _context.Books
.Include(a => a.BookAuthors)
.Include("BookAuthor.Author")
.Single(b => b.Id == id);
}