The first check is performed on the created MVC model, which is passed to the controller. MVC uses the ModelBinder class to build, populate, and validate client http form data in the model. Any failed validation will be returned to the client. After that, the correct model can be changed by the controller, so the second check is performed by EF when saving. I believe that when saved, the EF check is only triggered if the property is new or has different data with the original value.
In theory, it should be possible to have a custom MVV ModelValidator and intercept the Validate method to set the ValidationContext elements. However, I could not figure out how to do this. However, I found a slightly different solution that works for me. Perhaps it can be adapted to your needs.
In my case, I wanted EF DbContext (in my code its CmsEntities) to be available for validation methods, so I can query the database (and do a thorough business logic check). The controller has a DbContext, but the model check is called by ModelBinder before passing it to the controllers.
My decision:
1) Add the DbContext property to your Entity (using a partial class or in a base object from which all inherited objects are)
2) Create a custom ModelBinder that will output the DbContext from the controller and put it into the model
3) Register your custom ModelBinder in Application_Start ()
Now, inside any validation method, the model will have a filled DbContext. ๏
Custom ModelBinder
public class CmsModelBinder : DefaultModelBinder { protected override bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext) {
Global.asax.cs
protected void Application_Start() { ... ModelBinders.Binders.DefaultBinder = new CmsModelBinder(); }
Ritchied
source share