12

I have a model class. The related database table has a unique constraint on two fields (say Column1 and Column2). I am not sure what is the best way to validate the object before it is saved.

I am thinking to implement IValidatableObject and do this validation in the Validate method. Is it a good idea? I am not sure since it requires reading data from DB in a 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

Would you recommend using a separate validator class instead of using validation attributes?

https://stackoverflow.com/a/16679307/1131855

Community
  • 1
  • 1
Maxim Eliseev
  • 3,248
  • 4
  • 29
  • 35
  • Similar to: http://stackoverflow.com/q/9603131/150342 – Colin Dec 20 '13 at 10:53
  • @Colin - thank you for that. But I am not sure that the accepted solution there is very elegant (adding CustomValidate method to DbContext class – Maxim Eliseev Dec 20 '13 at 10:58
  • Maybe, but IMHO passing a context into the `IValidatableObject` is worse: http://stackoverflow.com/a/6497228/150342 If you think of `IValidatableObject.Validate` as the place to validate the object and `DbContext.ValidateEntity` as the place to validate the data repository as a whole then it ain't so bad. I can't comment on `FluentValidation` as I haven't tried it, so it may well be more elegant. – Colin Dec 20 '13 at 11:17
  • @Colin "Maybe, but IMHO passing a context into the IValidatableObject is worse" - I agree. This is why I decide to ask this question – Maxim Eliseev Dec 20 '13 at 11:20
  • 1
    As an aside, adding indexes via attributes is in the pipeline: http://entityframework.codeplex.com/workitem/57 – Colin Dec 20 '13 at 11:24
  • 3
    Once I start getting into these sorts of validation scenarios, I build out a service layer. `Data Annotations` and `IValidatableObject` are useful for input validation, but business rule validation should be broken out somewhere else. – Mister Epic Dec 20 '13 at 12:52

0 Answers0