0

我一直在研究使用 MVC 解决批量分配问题以及以正确方式做事的不同方法。

到目前为止,我认为最好的两种方法如下:(我也看过 AutoMapper)

1:Value Injecter - 这似乎做得很好,但也依赖于第三方库

2:使用 UpdateModel 方法并绑定到视图模型接口,该接口公开了域模型中所需属性的子集。http://www.codethinked.com/easy-and-safe-model-binding-in-aspnet-mvc

在我使用上述实践之一开始编写整个应用程序(无需花费一周时间来找出我真正喜欢哪个)之前,是否有人有使用这两种方法的实际经验,你会推荐哪一种?

4

2 回答 2

0

General consensus from all the reading I've done on this topic is that if you're going from a Entity or Domain Model (from your database) to a View Model to show on the form feel free to use automation tools like AutoMapper or whatever your preferred tool is to automate it.

If you are however going from a Input or Form Model (the object populated via the automatic model binding) back into to your Entity or Domain Model, do not automate this. It's a slippery slope to navigate correctly and can result in your automation tool mapping over fields that were not intended/permitted. Everything I've read about this (and various implementations myself) suggest the best practice is to do this manually/explicitly. It's pretty straight forward and object initializers can make it very easy to read.

var person = new Person()
{
    PersonId = model.PersonId,
    FirstName = model.FirstName,
    LastName= model.LastName
}

personService.UpdatePerson(person);

Something along that line.

于 2013-02-01T22:23:19.670 回答
0

在只有与字符串/int 属性匹配的文本字段的简单场景中,任何事情都可以。

但是,当您在视图模型上有与模型中的对象(数据库中的 FK)匹配的属性时,它会变得更加复杂,您可能需要从数据库中提取某些单独道具的数据并将该对象的某些属性映射到视图模型, 像这样的东西。

prodinner asp.net mvc 演示应用程序在 Mapper 类中使用 valueinjecter,有一个 pdf 解释了这种方法,你可以在这里下载:http: //prodinner.codeplex.com/

于 2013-02-01T15:58:18.193 回答