我正在尝试编写一个Linq,它返回加入3个表的结果
有'书','作者'实体。 1本书可以有很多作者,1位作者可以写很多书
我想获得一个'BooksAuthors'对象,该对象具有书名和撰写该书的作者列表。我当前的linq是(但它什么也没有返回,我得到NullPointer异常)
BooksAuthors = db.tblBooks.SelectMany(
book => book.Authors,
(book, author) => new Books
{
BookID = book.BookID,
BookName = book.BookName,
Authors = book.Authors
}),
其他课程:
public class Author
{
public virtual int AuthorID { get; set; }
public virtual string AuthorName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public class Book
{
public virtual int BookID { get; set; }
public virtual string BookName { get; set; }
public virtual ICollection<Author> Authors { get; set; }
}
public class Books
{
public int BookID { get; set; }
public string BookName { get; set; }
public IEnumerable<Author> Authors { get; set; }
}
public class LibraryDb : DbContext
{
public DbSet<Book> tblBooks { get; set; }
}
答案 0 :(得分:0)
这应该返回一个IEnumerable类型的Books,其中包含一个Authors列表。
IEnumerable<Books> x =
db.tblBooks.Select(t => new Books {BookID = t.BookID, Authors = t.Authors, BookName = t.BookName});