-1

I'm using Silverlight + EntityFramework + RIA Services in a business application. The underlying database tables include the Humans table and the HumanAddresses table. Every human can have one or more addresses of different types (e.g. home, job, place of birth, etc). At least one address of type "Home" must always be present.

The UI allows to edit, remove and add new several addresses of a given human before submitting. I need to perform validation to find out whether these changes violate the forenamed rule. What is the best way to do this?

I tried using CustomValidationAttribute, but it allows (AFAIK) only entity-level validation, not validation across multiple entities, some of which are to be deleted, while others are to be added or modified.

Myrtle Oak
  • 11
  • 2

1 Answers1

1

If you need access to other entities then you need to override ValidateEntity in your database context. This is called for every entity that has been changed when you call SaveChanges().

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
    DbEntityValidationResult result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>());
    result = base.ValidateEntity(entityEntry, items);
    //Do your validation
    if(invalid)
    {
        result.ValidationErrors.Add(new DbValidationError("Property", "Error Message"));
    }
    return result;
}

Here are the validation options in EF http://msdn.microsoft.com/en-us/data/gg193959.aspx

Britton
  • 2,965
  • 2
  • 22
  • 24