1

使用 MVC 并将数据转换为 ViewModel 时,这是公认的方法吗?

目前我正在使用 AutoMapper 来执行此操作并且效果很好。但是我确实在一篇博客文章中看到(我认为是 Rob C)在 ViewModel 上有一个构造函数,它获取所需参数的数量,然后生成 ViewModel

例如 var RetViewModel = new ViewModel(MyObject);

这似乎是一种体面的做法,想法?

4

2 回答 2

3

“公认的方式”通常是最适合您的方式。

我从未听说过 AutoMapper,当我研究它时,我得到的是它通过遵循某种约定来创建神奇的对象映射。

截屏地址: http ://www.dnrtv.com/default.aspx? showNum =155

注意:我只看了大约一半的截屏视频,所以我对 AutoMapper 的想法有些不完整。

我个人不想使用它,因为它需要我编写额外的代码来映​​射/“展平”对象属性(代码,IMO,最好留在构造函数逻辑中)。在截屏示例中,该代码通常放置在可能导致膨胀的控制器的操作方法中。(我喜欢瘦控制器/操作)

我使用您在帖子中提供的方法,让模型的构造函数获取一个对象并完成所有工作。

此外,我总是创建一个不带参数的空构造函数,以便我可以手动设置 ViewModel 对象的属性值。

例子:

CustomViewModel myModle = new CustomViewModle
{
    Property1 = "Something",
    Property2 = 3,
    //etc..
};

总而言之,尝试两种方法,看看哪种方法适合你。AutoMapper 是一个好主意,我可以看到它在许多情况下都有帮助,但是,我认为在某些时候使用它时,如果要使用对象构造函数,您将使用它编写尽可能多的代码。

于 2009-12-02T00:03:18.190 回答
1

Well, the "officially recommended" approach is to let the model binding mechanism handle that for you. That is simpler and automates the process. The model will have to expose its properties to be read-write for the binder to be able to initialize it.

The second option you're talking about will probably take benefits of making your models immutable objects. That is, you make all properties read-only and initialize them once via constructor parameters. This will require that you look into FormCollection directly to pull out the submitted values. That is more work but has its own advantages like being one type of defensive programming.

I can't say which way is better, both are options. I personally prefer the second style for now.

于 2009-12-01T09:17:21.427 回答