8

我正在使用数据注释来检查正在输入的数据,但是当涉及到更自定义的数据验证方式时,我被卡住了。

我需要对数据库运行查询以查看那里是否存在东西,然后如果出现“自定义 db-check 错误”,例如“公司名称已存在”,则向用户报告

如何与数据注释一起实现这样的事情?

我使用 3.5sp1 附带的 linq 和实体框架完成了所有查询等

/米

4

1 回答 1

12

扩展数据注释的自定义属性

您将必须编写自己的属性,这些属性将针对数据存储验证您的对象实例。

确保你的类继承System.ComponentModel.DataAnnotations.ValidationAttribute类:

public class MustNotExist: ValidationAttribute
{
    ...
}

警告

当我需要验证对象在数据存储中是否唯一时,我遇到了类似的情况。但是这种验证在实体类本身上是不可能的,因为它应该只适用于那些正在创建的实体,而不是当你已经从数据存储中返回你的实体时。

我的解决方案是有一个单独的接口、类和属性。

public interface IExternalValidator ...

class DBUniqueValidator: IExternalValidator ...

class ValidateExternallyAttribute: FilterAttribute, IActionFilter
{
    ...
    public ValidateExternallyAttribute(Type validatorType, Type entityType) ...
    ...
}

我能够将我的属性放在获取实体参数的控制器操作上。过滤动作属性然后检查控制器动作参数(它可以轻松访问它们的类型和值)并针对正确的参数(属性定义中提供的类型)运行外部验证器,并在验证失败时填充 ModelState 错误。

[ValidateExternally(typeof(DBUniqueValidator), typeof(User))]
public ActionResult RegisterUser(User newUser)
{
    if (!this.ModelState.IsValid)
    {
        // act accordingly - probably return some error depending on model state errors
    }
    // register new user in data store
}

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.

于 2009-12-15T12:28:53.523 回答