EF将所有子记录与父成员一起收集到列表中

时间:2015-01-22 16:32:28

标签: c# linq entity-framework

假设

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  
}

我需要一个像viewModel:

BooksViewModel
{
     int BookId
     int AuthorId
     string AuthorName
     string BookName
}

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

我知道,并且已经看过SelectMany获取所有儿童书籍的清单;

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

但是当我需要在该列表中包含父表数据(如作者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,
                });

这是明智之举吗?

2 个答案:

答案 0 :(得分:2)

我会在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
    })

答案 1 :(得分:1)

试试这个: -

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();

您可以使用Book展平SelectMany对象,并将其与Author对象一起投影。