views:

228

answers:

1

I'm not interested in answers concerning client side validation or model binding. Really, this question could apply to any data access class library outside of MVC, but the issues are similar, I think.

I'm using the Repository pattern currently for data access with my entities (models). Currently the repositories handle all of the CRUD operations, but I think I'd like for my models to be responsible for saving themselves in order to do validation. How should I handle this?

I could add a IsValid method in my models that the repositories could call that could then run all of my business logic before the repository saves the model, but then nothing FORCES the repositories to call this validation logic, right?

If I want the models to have a Save method, then what's the proper way for them to save themselves? They shouldn't call back up to the Repository should they?

Any thoughts on how I should handle this?

Thanks!

+2  A: 

There's nothing inherently wrong with allowing the model to validate save operations; it is even feasible to return false or throw an exception. The difficulty arises when you must then provide feedback to the user as to why their entered data is not valid.

Validation can and should occur in the view first. This can readily be done client-side using jQuery libraries. But the data must still be validated server-side after the user submits, and if there are still problems with the data, you must still provide an explanation to the user.

Because of the need to provide user feedback, server-side validation of this sort can be effectively provided in a View Model object. This data object serves two purposes: first, it encapsulates the data that passes between the view and the controller in a strongly-typed object. Second, it provides a convenient place to perform validation, without requiring validation logic in either the controller or the view.

If Linq to SQL is used, the View Model can be an extension of the actual data model class, using the partial keyword in C#. This allows you to use the existing ORM capabilities of the generated Linq to SQL class, while tacking on the additional validation functionality. I assume that this works the same way in the Entity Framework, and other ORMs.

View Models are described in the NerdDinner tutorial here: http://nerddinnerbook.s3.amazonaws.com/Part6.htm

The validation process is described here:
http://nerddinnerbook.s3.amazonaws.com/Part3.htm

Robert Harvey
Robert - I like this answer. Having worked with asp.net mvc lately I have found validation difficult in terms of where to do it and I think your point about using a ViewModel represents the best way to go for non-trivial apps...
Remnant