这里有很多关于这个主题的精彩帖子,我已经尝试全部阅读。我是一名资深的 n 层开发人员,但尝试开始使用 MVC3/EF 应用程序。我已经通过 EF POCO 生成器(T4)生成了 POCO。我还将 ViewModel 绑定(bind)到我的 View ...我的 View 中没有 EF 内容。我的问题与验证有关(仅限 U/I)。我喜欢 DataAnnotations 的想法并想使用它们。但是,为了正确使用它们,我必须在我的 ViewModel 中使用它们。根据我在这个网站和其他网站上看到的建议,我必须将 POCO 中的所有属性复制到我的 View 模型中,并在那里进行注释。为了让这件事变得更容易,我看到了很多使用 AutoMapper 的建议,让这个繁琐的映射变得更容易忍受。
我的想法基本正确吗?
最佳答案
I'm also binding ViewModels to my Views...no EF stuff in my Views
正确。 理想情况,您的 POCO 不应出现在您的 View 上。
I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels
正确。您的 POCO 上不应有任何数据注释。
为什么?您是否总是绑定(bind) POCO 上的所有属性?请记住,ViewModel 仅为 View 提供服务。因此,如果您有一个表单来提交订单,则 ViewModel 应该只包含保存该订单所需的内容。 AutoMapper 和您的自定义代码的组合可以将其映射到您的 POCO。From the advice I see on this site and others, I'll have to replicate any properties from my POCOs into my view models and do my annotations there
To make this easier I've seen lots of suggestions to use AutoMapper to make this tedious mapping more bearable
@Craig 是对的,它与数据注释无关。 AutoMapper 通过几行配置将您的 ViewModel 映射到您的域模型。
关于entity-framework-4 - 使用 POCO 和 ViewModel 的 MVC3 EF 模型优先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5252780/