使用 POCO 和 ViewModel 的 MVC3 EF 模型优先
这里有很多关于这个主题的精彩帖子,我已经尝试全部阅读。我是一名资深的 n 层开发人员,但尝试开始使用 MVC3/EF 应用程序。我已经通过 EF POCO 生成器(T4)生成了 POCO。我还将 ViewModel 绑定到我的视图...我的视图中没有 EF 内容。我的问题与验证有关(仅限 U/I)。我喜欢 DataAnnotations 的想法并想使用它们。但是,为了正确使用它们,我必须在我的 ViewModel 中使用它们。根据我在这个网站和其他网站上看到的建议,我必须将 POCO 中的所有属性复制到我的视图模型中,并在那里进行注释。为了让这件事变得更容易,我看到了很多使用 AutoMapper 的建议,让这个繁琐的映射变得更容易忍受。
我的想法基本正确吗?
Lots of great posts out here on this topic and I've tried to read them all. I'm a long time n-tier developer but trying to swing into action with an MVC3/EF application. I've generated POCOs via the EF POCO generator(T4). I'm also binding ViewModels to my Views...no EF stuff in my Views. My question has to do with validation (U/I only). I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels. 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.
Do I pretty much have the right idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正确。 理想情况,您的 POCO 不应出现在您的视图上。
正确使用它们。 POCO 上不应有任何数据注释。
为什么?您是否总是绑定 POCO 上的所有属性?请记住,ViewModel 仅为视图提供服务。因此,如果您有一个表单来提交订单,则 ViewModel 应该只包含保存该订单所需的内容。 AutoMapper 和您的自定义代码的组合可以将其映射到您的 POCO。
@Craig 是对的,它与数据注释无关。 AutoMapper 通过几行配置将您的 ViewModel 映射到您的域模型。
Correct. Ideally, your POCO's should not be on your Views.
Correct. There shouldn't be any data annotations on your POCO's.
Why? Are you always binding to all of the properties on your POCO's? Remember, the ViewModel is to serve the View only. So if you have a form to submit an order, the ViewModel should only contain what is required to persist that Order. A combination of AutoMapper and your custom code can then map that to your POCO.
@Craig is right, it has nothing to do with Data Annotations. AutoMapper maps your ViewModel to your domain models with a few lines of configuration.
AutoMapper 仅涉及从实体到视图模型的转换,反之亦然。它只是替换代码,例如类型之间的自定义转换运算符。您仍然需要创建视图模型并使用正确的数据注释标记属性。
AutoMapper is only about transformation from entity to view model and vice versa. It is just replacement of code like custom conversion operator between types. You will still have to create your view models and mark properties with correct data annotations.