EF将所有子记录与父成员一起收集到列表中 [英] EF Gather all child records into list with a parent member

查看:142
本文介绍了EF将所有子记录与父成员一起收集到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设

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:

and that I need a viewModel like:

BooksViewModel
{
     int BookId
     int AuthorId
     string AuthorName
     string BookName
}

如何使用LINQ满足该视图模型?

How do I fulfil that view model with LINQ?

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

I know, and have seen SelectMany to get the list of all children books;

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

但是当我需要在该列表中包括作者ID和AuthorName之类的父表数据时,我感到很困惑.

But I am getting stumped when I need to include parent table data in that list like Author Id and AuthorName.

我如何构造LINQ以包括那些?

How do I structure the LINQ to include those?

           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,如下所示:

I would put a property on the Book entity to reference the Author like so:

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
    })

这篇关于EF将所有子记录与父成员一起收集到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆