locked
EF Code First entity validation methods - how to choose RRS feed

  • Question

  • I was reviewing an older article here (http://msdn.microsoft.com/en-nz/data/gg193959) on validation in EF 4.1 and near the end it has an interesting quote on triggering the validations:

    "DbContext.GetValidationErrors will trigger all of the validations, those defined by annotations or the Fluent API, the validation created in IValidatableObject (e.g., Blog.Validate), and the validations performed in the DbContext.ValidateEntity method."

    Since you trigger all of the validations with a call to GetValidationErrors, why would you choose one method over the other? I suppose the Fluent API should be excluded because (I believe) it cannot perform the complex validations at the entity level like IValidatableObject and DbContext.ValidateEntity. But both the entity validation methods appear to cover the same ground.

    So to rephrase, between IValidatableObject and DbContext.ValidateEntity, is there a compelling reason to pick one over the other?

    Wednesday, November 2, 2011 9:38 PM

Answers

  • After reading those links I think they both do the same thing but the main difference is access. If you have access to the POCO then you can implement IValidatableObject. If you don't have access then you can fall back to using DbContext.ValidateEntity . But one thing I didn't catch on to originally is using dbContext also allows you (obviously) full access to the context so you are able to do more robust validation like searching for duplicate values prior to an insert.

    • Marked as answer by pretzelb Thursday, November 3, 2011 3:54 PM
    Thursday, November 3, 2011 3:54 PM

All replies