使用数据注释进行自定义验证
我正在使用数据注释来检查正在输入的数据,但当涉及到更自定义的数据验证方式时,我陷入了困境。
我需要对数据库运行查询以查看其中是否存在内容,然后如果出现“自定义数据库检查错误”,例如“公司名称已存在”,则向用户报告,
我如何与数据注释?
附带的 linq 和实体框架完成了所有查询等
我使用 3.5sp1 /M
I'm using data annotations to check data that's being entered, but I'm stuck when it comes to more custom way to validate data.
I need to run queries against database to see if stuff exists there or not, and then report back to user if a "custom db-check error" appears, such as "The Companyname already exists"
How can I implement such a thing together with dataannotations?
I have all the queries done etc using linq and entity framework that comes with 3.5sp1
/M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
扩展数据注释的自定义属性
您必须编写自己的属性来根据数据存储验证对象实例。
确保您的类继承 System.ComponentModel.DataAnnotations.ValidationAttribute 类:
注意
当我需要验证对象在数据存储中是否唯一时,我遇到了类似的情况。但是这种验证在实体类本身上是不可能的,因为它应该只适用于正在创建的那些实体,但不适用于已经从数据存储返回实体时。
我的解决方案是有一个单独的接口、类和属性。
我能够将我的属性放在获取实体参数的控制器操作上。然后,过滤器操作属性检查控制器操作参数(它可以轻松访问其类型和值),并根据正确的参数(在属性定义中提供的类型)运行外部验证器,并在验证失败时填充 ModelState 错误。
这样我就能够仅对那些实际需要的操作运行外部验证,并且这种技术还帮助我的控制器操作代码保持干净和简短。我所要做的就是检查是否存在任何模型状态错误。
Custom attributes that extend data annotations
You will have to write your own attributes that will do the validation of your object instance against data store.
Make sure your classes inherit
System.ComponentModel.DataAnnotations.ValidationAttribute
class:Caution
I've run into a similar situation when I needed to validate that the object is unique within data store. But this kind of validation wasn't possible on the entity class itself, since it should only work for those entities that are being created but not when you return your entity from the data store already.
My solution was to have a separate interface, class and attribute.
I was able to place my attribute on controller actions that get entity parameters. Filter action attribute then checks controller action parameters (it can easily access their types and values) and runs external validator against correct parameters (provided types in attribute definition) and populates ModelState errors when validation fails.
This way I was able to run external validation only on those actions that actually needed it, and this technique also helped my controller actions code to stay clean and short. All I had to do is to check if there are any model state errors.