Using Data Annotations Validation Manually and Object Graphs

牧云@^-^@ 提交于 2019-12-10 10:19:22

问题


Let's assume that I have two simple classes:

public class CustomerDetails
{
  [Required]
  public string Address
  {
    get;
    set;
  } 
}

public class Customer
{
   public Customer()
   {
     Details = new CustomerDetails();
   }

   [Required]
   public string Name
   {
     get;
     set;
   }
   public CustomerDetails Details
   {
     get;
     private set;
   } 
}

When I try to manually validate Customer class in a Console application in this way:

var customer = new Customer() { Name = "Conrad" };
var context = new ValidationContext(customer, null, null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(customer, context, true);

Then -even though I chose to validate all properties of the customer instance- Validator just validates the Name property of the customer instance, but not the Address property of the Details.

Is this by design or am I missing something here? Moreover, if this is by design then is there a robust way to manually validate the full object graph decorated with validation attributes, including nested types instead of using validator for the whole object graph manually?

Please note that this is tested within a Console application and not an ASP.NET MVC application.

Kind regards.


回答1:


I had almost the same problem but with the collection of nested objects. I was able to resolve it by implementing IValidatableObject on a container class. In your case it's slightly easier. Something like this:

public class Customer : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var context = new ValidationContext(this.Details, validationContext.ServiceContainer, validationContext.Items);
        var results = new List<ValidationResult>();
        Validator.TryValidateObject(this.Details, context, results);
        return results;
    }
}

Hope this helps.



来源:https://stackoverflow.com/questions/6938877/using-data-annotations-validation-manually-and-object-graphs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!