0

基于 MVC Music Store 示例,我尝试将专辑与流派一起预取,但仅从专辑中读取特定数据,而不是完整实体。

这是 EF 查询:

public ActionResult Browse(string genre)
{
   // Retrieve Genre and its Associated Albums from database
   var genreModel = storeDB.Genres.Include("Albums").Single(g => g.Name == genre);
   return View(genreModel);
}

假设我有一个视图模型:

public class AlbumViewModel
{ 
   public string Title { get; set; }
   public decimal Price { get; set; } 
}

我将如何更改 EF LINQ 查询以获取流派信息并包括专辑但只选择视图模型中列出的数据,而不是整个实体?

要执行 View Model 部分,我会执行类似 (VB) 的操作:

From a In storeDB.Albums
Where a.Genre = genre
Select New AlbumViewModel With {
     .Title = a.Title,
     .Price = a.Price,
})
4

1 回答 1

0

应该是这样的:

(from g in storeDB.Genres
where g.Name == genre
select new {
    Genre = g,
    Albums = g.Albums.Select(a => new { Title = a.Title, Price = a.Price })
})
于 2012-05-08T02:49:45.697 回答