首先使用数据注释和代码的自定义验证属性

时间:2011-08-03 16:47:43

标签: c# c#-4.0 annotations entity-framework-4.1

我在C#4.0中使用customvalidation属性编写了一个自定义验证方法。我正在使用Entity Framework 4.1的代码。但是,自定义验证属性方法是静态的。如何在引用同一类中的其他非静态字段时验证类中的其他逻辑。

即。

public class Foo
{
   [CustomerValidation(typeOf(Foo), "ValidatePoints"]
   public string Points { get; set; }

   public string AdvancedPoints { get; set;}

   public static ValidationResult ValidatePoints(string _Name)
   {
       if (_Name != AdvancedPoints) //Note that AdvancedPoints here is non-static and                                         should not be here. but i want to know how i can achieve this. 
       {     
           return ValidationResult.Success;
       }
       else
           return new ValidationResult("Wrong entry");
}

}

2 个答案:

答案 0 :(得分:0)

您可能希望查看IValidatableObject

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject.aspx

它允许您为给定的类添加类或多属性验证。

答案 1 :(得分:0)

你可以在其中使用带静态方法的类。并使用该方法验证类,如下所示:

 [CustomValidation(typeof(Validate_Foo), "Validate")]
 public class Foo 

 public class Validate_Foo
{
    public static ValidationResult Validate(Foo obj, ValidationContext vc)
    {
         return ValidationResult.Success;
         //or return new ValidationResult("Error"); 
    }
}