开发者

Best practise for validating Entity Framework entities in ASP.Net MVC 3 using a repository pattern?

I have found on a couple of occasions when we add new properties to some of the entities then although we keep up to date on the validation logic (which is just in a service class for now) but we miss the part in the update logic where in the service class we retrieve the bind from the repository and set all the properties of the entity in the repo to the model and then try and save. The effect is that the new field never gets saved because we forgot to do the assignment in the update logic.

The controller class has a nice UpdateModel(model) method which will do it all for you and make sure that it gets all the properties. This works great but it doesn't get around the problem of extra validation and the fact that the service gets the entity from the repo.

What is the best practise in the scenario where you want to use the UpdateModel method, want to do validation and are trying to stick th开发者_开发技巧e to repository pattern. I have purposefully left out the service class because I don't mind ditching it. It seems to be way to much hassle for what it is worth.


You can implement IValidatableObject interface in your Entity classes and/or view models.

Both EF 4.1 and MVC 3 are aware of this interface.

MVC will call the Validate moethod in the UpdateModel method and if there are any validation errors it will throw an exception. MVC will even put the validation error on the view. MVC Validation

EF will also call this method before insertions and updations are saved.

You can put all complex validation rules(which can not be declared using Data Annotation) in Validate method


Any reason you can't go with the existing data annotations that integrate nicely with MVC?

http://www.scribd.com/doc/55504020/29/Using-MetaData-Partial-Classes-with-Entity-Framework If you want to not rely on the existing model binding to set this information for you then a call to TryUpdateModel will update your modelstate which then you can use ModelState.IsValid.


Have you looked at AutoMapper, it is meant for this kind of thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜