3

So I have the following objects

public class Person : IValidatableObject 
{

[Required]
public string Name {get;set;}
[Required]
public string Status {get;set;
public Address Address {get;set;}
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {

            if (Status != "Addressless" && Address == null)
            {
                yield return new ValidationResult("An address is required if this person is not addressless");
            }
        }
}

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

Now, my problem is that Address values are required because if the person does have an address, EF Code First needs not null values in the DB in the Address table. This seems to be causing an issue because a Person does not need an address, so if they are "Addressless", there should be no Address validation, but validation still kicks off because Address has required fields.

Is there a way around this?

RJP
  • 4,016
  • 5
  • 29
  • 42
  • Maybe it is enough to set the one-to-one relationship as optional: http://stackoverflow.com/questions/6021135/ef-code-first-1-to-1-optional-relationship – Tallmaris Nov 12 '12 at 16:04
  • It is currently set to optional and that works fine with testing. – RJP Nov 12 '12 at 16:07

2 Answers2

2

Cause

As chris-shouts decribed in answer to similar question.

When validating an object, the following process is applied in Validator.ValidateObject:

  1. Validate property-level attributes
  2. If any validators are invalid, abort validation returning the failure(s)
  3. Validate the object-level attributes
  4. If any validators are invalid, abort validation returning the failure(s)
  5. If on the desktop framework and the object implements IValidatableObject, then call its Validate method and return any failure(s)

Your case

So in your case Required attribute validation prevents your IValidationObject to be checked.

Possible solution

Possible solution could be to move your required check for address in Validate method

Community
  • 1
  • 1
muphblu
  • 21
  • 1
  • 5
1

The issue is that the Required attributed are inherited. So even though Address is not required, when you bind to the view the individual properties of an address are required.

Your best bet is to make a view model for Address and not have any attributes, and put some validation logic in a separate class or even in your controller that verifies your domain logic. You can add validation data using ModelState.AddModelError.

James
  • 5,622
  • 9
  • 34
  • 42