实体到视图模型的映射真的需要AutoMapper/ValueInjector吗?

本文关键字:AutoMapper ValueInjector 真的 视图 模型 映射 实体 | 更新日期: 2023-09-27 18:02:57

我想知道是否真的需要使用一些对象到对象映射器,当映射实体框架实体到ViewModels。周围的样本通常显示1个实体映射到1个视图模型。但现实生活通常是不同的;因为我们通常需要连接多个表并从每个表中选择一些列。(我使用POCO实体和asp.net 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();
        }
    }

实体到视图模型的映射真的需要AutoMapper/ValueInjector吗?

不,真的不需要。只要适合你,满足你的要求,就足够好了。

Automapper和类似的解决方案允许您提取映射逻辑以分离层并使其自动化。有时这是一件好事,有时则不然。

在您展示的示例中没有,它执行自定义投影和连接。在我的项目中,它通常看起来像这样:

using (MyEntities context = GetMyEntites())
{
    var query = context.Table1
        .Where(t1 => t1.FilterColumn == filter1)
        Project().To<MyViewModel>();
    return query.ToList();
}

查看更多信息:https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions