requiredif实体框架空字段

时间:2013-02-22 20:03:58

标签: c# .net entity-framework

我正在使用MVC中的自定义验证验证基于另一个字段的字段,我遇到了这个实现:

 public class RequiredIfAttribute : ValidationAttribute
    {
        private String PropertyName { get; set; }
        private String ErrorMessage { get; set; }
        private Object DesiredValue { get; set; }

        public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
        {
            this.PropertyName = propertyName;
            this.DesiredValue = desiredvalue;
            this.ErrorMessage = errormessage;
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            Object instance = context.ObjectInstance;
            Type type = instance.GetType();
            Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (proprtyvalue.ToString() == DesiredValue.ToString())
            {
                return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }
    }

我有一个简单的类定义如下:

public class Person
{
    public int PersonID { get; set; }
    public string name { set; get; }
    [RequiredIf("name","","Address is required")]
    public string addr { get; set; }
}

当我运行该页面时,出现Object reference not set to an instance of an object.错误,但将行更改为[RequiredIf("name","John","Address is required")]会产生预期结果。我的问题是,你如何用它来检查字段是否为空。

我也尝试将行更改为[RequiredIf("name",null,"Address is required")]但我收到同样的错误。

2 个答案:

答案 0 :(得分:2)

这似乎有效:

protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            if (value != null) { return ValidationResult.Success; }

            Object instance = context.ObjectInstance;
            Type type = instance.GetType();
            Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (proprtyvalue == null) {
               return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }

答案 1 :(得分:0)

你没有发布你正在测试的实际Person实例,所以我只是猜测:在尝试调用ToString()之前,确保PropertyName的 proprtyvalue 不为null。因此, Person.Name 不能 null