【问题标题】:Custom validation attribute using data annotations and code first使用数据注释和代码的自定义验证属性
【发布时间】:2011-08-03 16:47:43
【问题描述】:

我在 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");
}

}

【问题讨论】:

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


    【解决方案1】:

    你可能想看看IValidatableObject

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

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

    【讨论】:

      【解决方案2】:

      您可以使用包含静态方法的类。并使用该方法来验证类,如下所示:

       [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"); 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-08
        • 1970-01-01
        相关资源
        最近更新 更多