实体框架查询结果整形

时间:2012-05-08 02:31:44

标签: asp.net-mvc entity-framework linq-to-entities

根据MVC音乐商店样本,我试图预先获取专辑和类型,但只读取专辑中的特定数据,而不是整个实体。

这是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);
}

假设我有一个View Model:

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

如何更改EF LINQ查询以获取流派信息并包含相册,但只选择视图模型中列出的数据,而不是enitire实体?

要做View Model部分,我会做类似(VB)的事情:

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

1 个答案:

答案 0 :(得分: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 })
})