Entity Framework – Where to Put Custom Validation in ASP.NET MVC 3

asp.net-mvc-3centity-frameworknet

I am using MVC3 and Enitty Framework 4 with the Database first approach. It created the context template with its own validation for the fields based on the database. My question is where should I put the other validation based on the buisness logic. Should I put it in the Context.tt file, should it go in the controller or should it go in a seperate model?

Best Answer

At a minimum, business logic validation should go within the Controller for the framework you're using. If the validation logic is portable, creating a separate validation module, called by the Controller, would also be okay.

In general, place the validation logic as close as possible to the layer it affects. Likewise, validate items at the most appropriate layer (appropriate defined by what's being affected). The concept is a related to encapsulation and the SOLID principles. The goal is to allow changing out the individual components as needed, as well as making the validation logic more portable.

To be a little more clear, if there's validation logic to protect the database from errant changes, then that logic should be placed within (or called from) the Model. Likewise, input validation belongs within the View.

Some validation logic can pull double (or triple) duty or would be common across multiple modules in the same layer. It's appropriate to create a separate module for that logic. At the risk / expense of duplicate checks, I would still have each layer validate for the aspects it is responsible for.