I am writing some code using the new Entity Framework 4.1 code first model (where you simple objects to represent your database). I am using the System.ComponentModel.DataAnnotations to set rules such as required fields, validation with regular expressions, range validation, etc.

However, I could not find how you would implement the custom, “On[Property]Changing” patterns that is common in prior editions (using partial classes and partial methods). After a lot of looking, I stumbled upon the answer.

You use the new CustomValidation attribute. You can mark your property with this attribute as follows:

[CustomValidation(typeof(RegValidation), "ValidateAcceptTerms")]

public bool AcceptTerms { get; set; }

 

In this case, you are indicating that the validation code sits in the class, RegValidation inside the method, ValidateAcceptTerms.

 

You can then code this validation class as follows:

public class RegValidation

{

  public static ValidationResult ValidateAcceptTerms(bool isAccept)

  {

    if (isAccept)

    {

      return ValidationResult.Success;

    }

    else

    {

      return new ValidationResult(

          "You must accept the terms of service in order to continue.");

    }

  }

}

 

You return an instance of ValidationResult (either success or with an error message) to indicate the results. In this way, you can implement custom validation on your EF 4.1 code first properties.

Note: since your objects are just simple objects, you can also write the logic in your setter and raise a validation exception. This will prevent the object from saving. However, it will not automatically get your validation error into the view. The CustomValidation attribute will.