Is it a good idea to access the database in the IValidatableObject.Validate method?

I have a model class. A linked database table has a unique constraint for two fields (for example, Column1 and Column2). I am not sure what the best way to validate an object before saving it.

I am going to implement IValidatableObject and perform this check in the Validate method. Is that a good idea? I am not sure, since it requires reading data from a database in an entity class.

public class Class1 :IValidatableObject { [Key] public int ID { get; set; } [Required] public int Column1 { get; set; } [Required] public int Column2 { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { using (DatabaseContext db = new DatabaseContext()) { //access DB to check if this combination of Column1 and Column2 already exists } } } 

I am using MVC4 and EF 4.4.

UPDATE

Do you recommend using a separate validation class instead of using validation attributes?

stack overflow

+6
source share

All Articles