EF 将所有子记录收集到具有父成员的列表中

EF Gather all child records into list with a parent member

假设

Author
{
    int Id
    string Name
    bool Active
    bool ShowOnBookWall
    public virtual ICollection<Book> Books { get; set; }
}

Book 
{
    int id
    int AuthorId
    bool Active
    string Name  
}

我需要一个像这样的视图模型:

BooksViewModel
{
     int BookId
     int AuthorId
     string AuthorName
     string BookName
}

如何使用 LINQ 实现该视图模型?

我知道,并且看过 SelectMany 获取所有儿童书籍的列表;

db.Authors.Where(a => a.Active && a.ShowOnBookWall)
     .SelectMany(author => author.Books)
     .ToList();

但是当我需要在该列表中包含父 table 数据(如作者 ID 和作者姓名)时,我感到很困惑。

如何构造 LINQ 以包含这些?

           db.Authors.Where(a => a.Active && a.ShowOnBookWall)
                .SelectMany(author=> author.Books).ToList()
                .Select( w=> new BooksViewModel()
                {
                    AuthorName = db.Authors.First(ar => ar.Id == w.AuthorId).Name,
                    AuthorId = w.AuthorId,
                    BookId = w.Id,
                    BookName=w.Name,
                });

这样做明智吗?

我会在 Book 实体上放置一个 属性 来引用 Author,如下所示:

public class Book 
{
    public virtual Author Author { get; set; }
    ...
}

然后做类似的事情:

db.Books.Where(book => book.Author.Active && book.Author.ShowOnBookWall)
    .Select(book => new BooksViewModel
    {
        BookId = book.Id,
        AuthorId = book.Author.Id,
        AuthorName = book.Author.Name,
        BookName = book.Name
    })

试试这个:-

db.Authors.Where(a => a.Active && a.ShowOnBookWall)
          .SelectMany(author => author.Books,
               (authorObj, bookObj) => new { authorObj, bookObj })
          .Select(x => new BooksViewModel
                 {
                     AuthorName = authorObj.Name,
                     AuthorId = bookObj.AuthorId,
                     BookId = bookObj.id,
                     BookName = bookObj.Name
                 }).ToList();

您可以使用 SelectMany 展平 Book 对象并使用 Author 对象投影它。