最佳实践 - 实体框架 4 中的数据注释与 OnChanging
我想知道实体框架在数据验证方面的一般建议是什么。我对 EF 比较陌生,但似乎有两种主要的数据验证方法。
第一个是为模型创建一个分部类,然后执行数据验证并更新违反规则的集合。 http://msdn.microsoft.com/en-us/ 对此进行了概述library/cc716747.aspx
另一种是使用数据注释,然后让注释执行数据验证。 Scott Guthrie 在他的博客 http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx。
我想知道其中一种相对于另一种有什么好处。看起来数据注释将是首选机制,特别是当您转向 RIA 服务时,但我想确保我没有遗漏任何东西。当然,不排除将两者一起使用。
谢谢
约翰
I was wondering what the general recommendation is for Entity Framework in terms of data validation. I am relatively new to EF, but it appears there are two main approaches to data validation.
The first is to create a partial class for the model, and then perform data validations and update a collection of rule violations. This is outlined at http://msdn.microsoft.com/en-us/library/cc716747.aspx
The other is to use data annotations and then have the annotations perform data validation. Scott Guthrie explains this on his blog at http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx.
I was wondering what the benefits are of one over the other. It seems the data annotations would be the preferred mechanism, especially as you move to RIA Services, but I want to ensure I am not missing something. Of course, nothing precludes using both of them together.
Thanks
John
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我一直在使用 MVC 2 的 DataAnnotations,效果很好。我还没有尝试对实体对象进行部分验证,但我看到了它的用途。基本上,如果我在实体对象上创建分部类,我会使用它来默认数据,例如 GUID 标识符。或创建日期或修改日期。我想在分部类中添加验证可能会很有用,也许对于需要在实体层中进行的一些复杂验证来说,但即使如此,这些验证也可以在自定义验证器中完成。如果您使用 MVC 网站,那么我个人会使用数据注释。
I have been using DataAnnotations using MVC 2 and it works great. I have not tried the partial on an entity object for validation, but I see its uses. Basically if I create a partial class on an entity object I use it to default data such as a GUID identifier. or Create Date or modified Date. I guess it would be useful to add validations in the partial class perhaps for some complex validation that needs to happen in the entity layer but even then those validations could be accomplished in custom validator. If you are using an MVC website then I would personally use dataannotations.