Entity Framework 4.1 Code First – validate object model in controller
How开发者_开发问答 do I check that the model is correct for an object read from the database.
var myModelObject = theDB.myDbContext.myModelObject.Find(1234);
Now I would like to control if it is correct according to the rules / attributy in the model... but how?
It is expected that data read from database are correct according to validation rules because that validation rules also defines the mapping. Inconsistency can lead in some cases to exception in object materialization.
If you want to executed validation based on data annotations manually you can use:
using System.ComponentModel.DataAnnotations;
var results = new List<ValidationResult>();
var context = new ValidationContext(myModelObject, null, null);
bool isValid = Validator.TryValidateObject(myModelObject, context, results, true);
精彩评论