使用 EF POCO 类作为 MVC 2 模型(带有数据注释)
我有一个用 C# 编写的 4 层 Web 应用程序....Net 4.0:
- UI 层
- 业务层
- 数据访问层
- 实体层
我的数据层包含 edmx 我的实体层包含 POCO 对象(由 t4 脚本生成),并且该层在所有其他层中被引用。
例如,当创建 MVC 表单来创建新客户时......我的实体层中已经有了包含名字、姓氏等字段的客户类,但是自动生成的 POCO 类没有数据注释用于验证... IE [必需] 等,用于提交表单时
我现在的解决方案是创建与我的 poco 类几乎相同的新模型类,但也具有这些附加验证注释。
我想知道的是,是否有一种简单的方法可以在 MVC 模型(在 UI 层)中使用某些 POCO 对象,而无需几乎重写类......并且也无需修改生成这些 POCO 类的 t4 (因为我我还没跟上 t4) 的进度。
我从 stackoverflow http://automapper.codeplex.com/ 上的另一篇文章中看到了这一点...不确定如果这可以做到或者是最好的解决方案。
I have a 4 layered web application programmed in C#... .Net 4.0:
- UI Layer
- Business Layer
- Data access Layer
- Entities layer
My data layer contains an edmx
My entities layer contains my POCO objects (generated by a t4 script), and that layer is referenced in all other layers.
When creating an MVC form to create a new customer, for example.... I already have the customer class with fields for first name, last name, etc in my entities layer, but that auto-generated POCO class does not have data annotations for validation... I.E. [Required], etc. for when the form is submitted
My solution right now is to create new model classes that are pretty much the same as my poco classes but also have these additional validation annotations.
What I want to know is if theres an easy way to use certain POCO objects in the MVC model (in the UI layer) without having to almost rewrite the class... and also without modifying the t4 that generates these POCO classes (since I'm not up to speed on t4).
I saw this from another post on stackoverflow http://automapper.codeplex.com/ ... not sure if this will do it or is the best solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的 POCO 类是这样声明的:
那么如果您只是更改 T4 使其成为分部类,那么您可以在单独的文件中定义:
额外的两点 - 元数据类不必嵌套在您的分部中定义,我认为它更整洁。另外,类型不必在元数据类中匹配,因此如果您愿意,您可以将它们全部设置为对象(您可能会在网络上看到一些这样的示例)
If your POCO class is declared as such:
then if you just change the T4 to make it a partial class, you can then define in a separate file:
Two extra points - the metadata class doesn't have to be nested in the partial you define, I think it's neater though. Also, the types don't have to match in the metadata class, so you could make them all object if you wanted to (and you might see some examples on the web with it like this)
修改 T4 模板一点也不难。我最近遇到了同样的问题,决定稍微阅读一下 T4,然后修改模板以按照我需要的方式创建生成的属性(注释,在我的情况下使用 NotifyPropertyChange 等,因为我在MVC UI 和 Silverlight UI)。
即使您正在寻找不需要修改 T4 的解决方案,我也希望这有用。
Modifying a T4 template is not very hard at all. I recently faced the same issue and decided to read up on T4 a bit and then modify the template to create the generated properties the way I need them (annotations, and in my case with NotifyPropertyChange etc. as I use the same POCO objects in an MVC UI and in a Silverlight UI).
Even though you're looking for a solution that doesn't require modifying T4, I hope this is useful.