<分区> 分区>
我想知道在将 Entity Framework 实体映射到 ViewModel 时是否真的需要使用一些对象到对象的映射器。周围的样本通常显示 1-entity 映射到 1-viewmodel。但是现实生活通常是不同的;因为我们一般需要连接多个表,然后从每个表中选择一些列。 (我使用 POCO 实体和 ASPNET MVC)这是我经常用来将我的 linq 查询结果映射到 ViewModels 的方法。
public List<MyViewModel> GetSomeDataForView(string filter1)
{
using (MyEntities context = GetMyEntites())
{
var query = (from t1 in context.Table1
join t2 in context.Table2 on t2.Table1Id equals t1.Id
join t3 in context.Table3 on t3.Table2Id equals t2.Id
where t1.FilterColumn=filter1
select new MyViewModel
{
Property1 = t1.Column1,
Property2 = t1.Column2,
Property3 = t2.Column1,
Property4 = t3.Column1
});
return query.ToList();
}
}
