ASP.NET MVC 2 验证:元数据类型无法添加到标准 POCO CLR 类 - 有什么替代方法?
我正在使用实体框架并通过 T4 生成 POCO 类 - 这些类从无继承,并且非常简单(通过 vs 2010 中的模板创建)
我尝试使用元数据类型属性,以便我可以创建一个伙伴类,但是当我这样做时如果我删除了该属性,我将无法再看到我的属性!属性出现了。
无论如何,更深入地搜索我发现了微软的这个声明
关联的类必须与 EDM 或 LINQ-to-SQL 模型一起使用,因为 CLR 类型无法使用新属性标记现有属性。如果您直接使用 CLR 对象(有时称为普通旧 CLR 对象 (POCO) 类型),则可以将属性直接应用于模型
因此它似乎不起作用。无论如何,我很难在模型本身上插入数据注释,因为它是通过 T4 创建的,因此如果我编辑它,然后重新运行该工具,它将删除我的所有更改。
I am using Entity Framework and generating my POCO classes via T4 - these classes inherit from nothing and are very plain and simple (created via template in vs 2010)
I tried using the Metadatatype Attribute so I could create a buddy class but when I did this I no longer was able to see my properties... if I removed the attribute! the properties appeared.
Anyway, searching deeper I found this statement from Microsoft
The associated class must be used with EDM or LINQ-to-SQL models because CLR types cannot mark existing properties with new attributes. If you are working with CLR objects directly, sometimes referred to as Plain Old CLR Object (POCO) types, you can apply the attributes directly to the model
So it appears it doesn't work. Anyway it's difficult for me to insert my Data Annotation on the MODEL itself because it's created via T4 hence if I edit it and then re-run the tool it will remove all my changes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SO 和 MVC 博客圈有一个非常强烈的共识,即您不应该使用属性来注释您的业务/CRUD/域类。不仅您的整个 MVC 堆栈变得依赖于您的业务/数据库类,而且您很快就会遇到多个上下文场景(相同的模型,不同的验证规则),而仅使用单个模型无法验证这些场景。
为您的屏幕使用单独的视图模型,并对其进行注释。
根据您的评论:“模型本身的数据注释,因为它是通过 T4 创建的”
我想说的是,将数据注释放在视图模型上,不要管 POCO 模型。
There is a pretty strong consensus around SO and the MVC blogosphere that you shouldn't annotate your business/crud/domain classes with attributes. Not only is your entire MVC stack becoming dependent upon your business/database classes but you'll quickly end up with multiple context scenarios ( same Model, different validation rules ) that are impossible to validate with just a single model.
Use separate view models for your screens, annotate those.
Based on your comment: "Data Annotation on the MODEL itself because its created via T4 hence"
What I'm trying to say is put your dataannotations on your viewmodels, leave your POCO models alone.