假设
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,
});
这是明智之举吗?
答案 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
对象一起投影。