ViewModel对象到EF模型实体的转换在哪里?
我目前有一个基于 Entity Framework v4 实体的存储库(已实现 CRUD 和 GET 操作)。我正在为这些实体创建相应的视图模型。我应该把它们之间的转换/映射放在哪里?在控制器中或修改存储库以在其方法中执行映射并返回(或接受)视图模型类型的对象?
我应该这样做
public ActionResult Index()
{
var person = new PersonRepository().Get();
var personViewModel = new PersonViewModel();
personViewModel.InjectFrom(person)
.InjectFrom<CountryToLookup>(person);
return View(personViewModel);
}
还是这样做
public ActionResult Index()
{
var personViewModel = new PersonRepository().Get(); // returns object of type PersonViewModel
// and move this to repository
// var personViewModel = new PersonViewModel();
// personViewModel.InjectFrom(person)
// .InjectFrom<CountryToLookup>(person);
return View(personViewModel);
}
I currently have a repository based on Entity Framework v4 entities (CRUD and GET operations implemented). I'm in the process of creating the corresponding View Models for these entities. Where should I put the conversion/mapping between them? In the controller or modify the repository to perform the mapping in its methods and return back (or accept) the View Model typed objects?
Should I do this
public ActionResult Index()
{
var person = new PersonRepository().Get();
var personViewModel = new PersonViewModel();
personViewModel.InjectFrom(person)
.InjectFrom<CountryToLookup>(person);
return View(personViewModel);
}
or this
public ActionResult Index()
{
var personViewModel = new PersonRepository().Get(); // returns object of type PersonViewModel
// and move this to repository
// var personViewModel = new PersonViewModel();
// personViewModel.InjectFrom(person)
// .InjectFrom<CountryToLookup>(person);
return View(personViewModel);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会将其提取到控制器上的私有方法中,或者如果要在其他地方重用它,则将其放入服务类中。
我认为将其放在存储库中不是一个好主意,除非它不是通用的。这应该是因为在我看来通用存储库很摇滚!
I would extract it out into a private method on the controller or put it into a service class if it's going to be reused in other places.
I don't think it's a good idea putting it on the repository unless it's not generic. Which it should be because in my opinion generic repositories rock!
我永远不会将转换代码放入您的存储库中。
将两者混合只是将你所有小心的解耦都扔掉。
MVC 的书籍定义强烈暗示应该在控制器内部完成转换:
“控制器接收输入并通过调用模型对象来启动响应。控制器接受来自用户的输入并指示模型和视口执行操作基于该输入。”
I would never put transformation code into your repository.
Mixing the two is just throwing all of your careful decoupling away.
The book definition of MVC strongly implies transformation should be done inside the controller:
"The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input."