ASP.Net MVC 你在哪里从实体转换到视图模型? [英] ASP.Net MVC Where do you convert from Entities to ViewModels?

查看:21
本文介绍了ASP.Net MVC 你在哪里从实体转换到视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎解释了这一切,这是我尝试在我们的项目中工作的最后一件事.我们由一个包含类似功能的服务库构成.

Title pretty much explains it all, its the last thing I'm trying to work into our project. We are structured with a Service Library which contains a function like so.

        /// <summary>
        /// Returns a single category based on the specified ID.
        /// </summary>
        public Category GetCategory(int CategoryID)
        {
            var RetVal = _session.Single<Category>(x => x.ID == CategoryID);
            return RetVal;
        }

现在 Category 是一个实体(我们正在使用实体框架),我们需要将其转换为 CategoryViewModel.

Now Category is a Entity (We are using Entity Framework) we need to convert that to a CategoryViewModel.

现在,人们将如何构建它?你会确保服务函数返回一个 CategoryViewModel 吗?让控制器从服务中提取数据,然后调用另一个函数转换到视图模型?

Now, how would people structure this? Would you make sure the service function returned a CategoryViewModel? Have the controller pull the data from the service then call another function to covnert to a view model?

推荐答案

这是博客文章 我写道:

[AutoMap(typeof(IEnumerable<User>), typeof(IEnumerable<UserViewModel>))]
public ActionResult Index()
{
    // return all users
    IEnumerable<User> users = Repository.GetUsers();
    return View(users);
}

在这种情况下,相应的视图被强类型化为 IEnumerable.它使用 AutoMapper 来定义实体和视图模型之间的转换规则.至于 [AutoMap] 属性,它是一个自定义操作过滤器,它检查传递给视图的模型并应用适当的转换,以便视图只有视图模型.

In this case the corresponding view is strongly typed to IEnumerable<UserViewModel>. It uses AutoMapper to define conversion rules between entities and view models. As for the [AutoMap] attribute, it's a custom action filter which inspects the model passed to the view and applies the proper conversion so that the view has only the view model.

这篇关于ASP.Net MVC 你在哪里从实体转换到视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆