ASP.Net MVC您从哪里将实体转换为ViewModel? [英] ASP.Net MVC Where do you convert from Entities to ViewModels?
问题描述
标题几乎可以解释所有这一切,这是我要在我们的项目中尝试的最后一件事.我们的服务库结构如此,其中包含类似的功能.
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是一个实体(我们正在使用Entity Framework),我们需要将其转换为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?
推荐答案
以下是在这种情况下,相应的视图被严格键入为 IEnumerable< UserViewModel>
.它使用 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您从哪里将实体转换为ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!