0

我正在尝试编写一个从加入 3 个表返回结果的 Linq

有“书”、“作者”实体。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; }
}
4

1 回答 1

0

这应该返回一个带有作者列表的 Books 类型的 IEnumerable。

IEnumerable<Books> x =
            db.tblBooks.Select(t => new Books {BookID = t.BookID, Authors = t.Authors, BookName = t.BookName});
于 2013-07-30T18:29:43.723 回答