I'm using Entity Framework and a Model class, DonationForm, wrapped by a view model class "CreateDonationForm".
In keeping with the DRY principle, I have added the validation annotations on the Model class (not the just the view model), so that they will be reusable. However, not all of the properties on the class will always be used (some are in fact mutually exclusive). For example when a particular phone number property is relevant, I want to make it conform to a Regex annotation and be Required. But in a different situation I want to be able to get away with submitting (and persiting to the database) a null value.
Following this post: How do I use IValidatableObject?
I made the model class implement IValidatableObject and implemented custom validation to selectiely remove validation errors from the ValidationResult object (when the field was part of a group of fields that were not relevant given the user's other choice(s) on the form). It worked and I was able to get back List of ValidationResults where those errors had been expunged.
However, when I called SaveChanges() I get validation errors which prevent the save. The validation is still happening at the database/model class level. (The database was generated from the Model class using EF 4.1 Code First.)
How is it possible to acheive conditional formatting rules and still use Annotations on the Model class? This is essentially saying - apply these validation rules IF otherwise do not apply these validation rules. Please coach me here. I'm new-ish to MVC and I'm trying to do things the proper way. It seems like putting the validation on the view model and then mapping values onto the underlying model class might work; however, it doesn't feel right. I see big value in having the validation attributes on the Model class itself and lots of wasted, repetivitive work in placing the same annotations on both the create and update view models. It feels like I'm fighting MVC Fw here on something that ought to be easier. Any insights that you can provide would be greatly appreciated.
There is a lot of cool principles but sometimes small violation makes your life easier. Get rid of data annotations from your EF model and place them on your view model where they belong. You can still use IValidatableObject in view model and compose the validation from multiple reusable helper methods used by multiple view models (so you can still achieve DRY principle).
If you stubborn and really want to have validation in EF model turn off validation in EF and handle it in upper layer as you already do:
dbContext.Configuration.ValidateOnSaveEnabled = false;
EF level validation is for simple scenarios where your validation rules do not change among operations.
Related
I know that mvvm calls for having a ViewModel class that wraps a Model class, but I'm wondering why it's a better practice to do this rather than just enhancing the Model class directly via partial classes. I get that you might want the Model to be auto-generated from an ORM, but you can still put the ViewModel stuff in another file via a partial class, and doing this avoids the considerable overhead of maintaining a ViewModel for every Model. So I guess the question is: what's so bad about letting the Model have UI oriented code, as long as you separate it in the source code and don't use the UI aspects of the Model inappropriately?
The point is separation of concerns. Your ViewModel is built specifically for the needs of the UI; that means the data it contains is formatted specifically for the UI, whereas your Model is formatted directly for your persistence or domain logic.
In your situation, changing your model necesarily requires then that a change is also done to the view model; when separated, each can vary independently which reduces unintended side effects.
what's so bad about letting the Model have UI oriented code, as long as you separate it in the source code and don't use the UI aspects of the Model inappropriately?
Nothing if you have a complete set of unit tests and are willing to update all locations that are using your model if it changes, or if you can guarantee that your database will never change.
You can't really "enhance" your Model instead of using a viewModel. In theory you could, but it would be very bad code.
Just a simple example:
Imagine that you have a class User with only 2 fields: userName and password. This User class is your model.
But on your page you want to add one more field to edit/add the data: the password verification field.
So are you going to add password2 field into your User class?
That's bad!
Instead you better create a ViewModel binded to your View and based on the data of your ViewModel then you create the instance of your Model and process it in the other layers
I'm using DataAnnotations for validation of a custom class (LINQ to SQL auto generated) using the MetadataType tag on top of the class. I'm loving DataAnnotations and it works well in simple, common scenarios. E.g.
[MetadataType(typeof(Person_Validation))]
public class Person
But what if you need to have two different sets of validation rules applied to the class in different scenarios???
My situation: Some fields are mandatory on the www public-facing site, but not mandatory on the internal admin site. But both sites have a View which "Creates New" of the same object/class.
This is where it becomes DataAnnotations HELL surfaces..
I've tried using two different ViewModels with different validation applied to each of them, two classes that inherit from Person with different validation applied to each of them. But all roads seem to conflict with DRY principals and you end up somewhere along the line having the totally respecify all properties for the underlying class structure. You don't have to do this when you just have one validation rule set. So it very quickly becomes hell and not practical for complex objects.
Is this possible using DataAnnotations and what is the best DRY architecture?
Not sure what you mean by 'virtually duplicate and manually set each and every property manually in the original underlying class'. I've never liked the idea of buddy classes, and would personally recommend different view models for Admin and Public site (with appropriate validation set on each), and then mapping between the models using AutoMapper.
UPDATE:
Regading Automapper, the basic usage is something like this:
First you have to define your mappings. This lets automapper figure out in advance how to map objects. You only need to do this once in the application, so a good place to do this in an ASP.NET app is in Application_Start() in Global.asax. For each pair of classes you want to map between, call: Mapper.CreateMap<SourceType, DestinationType>();
Then, in your application code to do the map you just use:
var destinationObject = Mapper.Map<SourceType, DestinationType>(sourceOjbect);
I am using automapper to map my models to viewmodel classes to pass to my view.
My question really is where should the validation go? I was planning on using the MetaData decorations - a feature of mvc 2.
But either in the model or viewmodel? Or in both places?
Validation should be done minimum at the View Model because this is what you receive as action argument and contains the user input. You could also have validation at the model.
My answer would be ViewModel because Model can change (for example from using Linq2SQL to EF). This way when you plug another Model you still have your validation intact.
I personally have my validation 2 places using DataAnnotations. My model is not passed up to my view in full. I have separate models for my views and translate the data from the view model into the model. This way, I can put whatever I want in my view model and leave out the pieces I don't want to deal with.
My reasoning, however, is that I have a windows application and an web application using the same model. This way, the same set of validation rules govern the Model for all apps, and my view model can have slightly different rules if need be. Of course, this creates a "duplication of logic" - well, validation logic.
This way I don't have to rebuild the data that wasn't used on the page every trip back to the server or put it in hidden fields and inflate the size of my pages.
You should put validation that is specific to the UI in the ViewModel, and anything that is related to business process or database validation in the Model. These might overlap.
The model should implement the validation it needs to ensure that its state cannot become invalid; that validation most definitely belongs on the model.
for example, a book class must guarantee that its title must be between 1 and 50 characters, its id must be >= 0 etc.
business rules belong elsewhere (in your controllers if you only have the model view and controller layers). this might be something like a user cannot add more than 3 books if their email isnt verified.
validation in the view should be restricted to parsing user input for invalid data: anti xss, sql injection, out of range. etc
I was wondering what the general recommendation is for Entity Framework in terms of data validation. I am relatively new to EF, but it appears there are two main approaches to data validation.
The first is to create a partial class for the model, and then perform data validations and update a collection of rule violations. This is outlined at http://msdn.microsoft.com/en-us/library/cc716747.aspx
The other is to use data annotations and then have the annotations perform data validation. Scott Guthrie explains this on his blog at http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx.
I was wondering what the benefits are of one over the other. It seems the data annotations would be the preferred mechanism, especially as you move to RIA Services, but I want to ensure I am not missing something. Of course, nothing precludes using both of them together.
Thanks
John
I have been using DataAnnotations using MVC 2 and it works great. I have not tried the partial on an entity object for validation, but I see its uses. Basically if I create a partial class on an entity object I use it to default data such as a GUID identifier. or Create Date or modified Date. I guess it would be useful to add validations in the partial class perhaps for some complex validation that needs to happen in the entity layer but even then those validations could be accomplished in custom validator. If you are using an MVC website then I would personally use dataannotations.
I'm would like to use both EF and MVVM and am trying to see how they fit together. I can't find much in the way of examples so hope you guys can answer a few questions.
Let's say I have a single table in a database called Customer. I run the EF designer and get a data model.
The next step is to run some linq to get data out of the data model. Let's create a new class called CustomerRepository to do this.
Now I'm guessing the Model would call CustomerRepository.GetCustomers to get a list of customers.
Here is my question - CustomerModel has a list of customer objects that were defined by EF in the data model. How do I add validation attributes or any kind of validation to it?
There just seems to be a bit of a disconnect between EF and MVVM. I'm sure some of you have hit this before - any ideas? Any better ways of approaching this?
Cheers
Steve
The validation, the business rules, the presentation of your Customer object should live in the ViewModel that will serve as a controller or presenter for your View.
In terms of how to create that ViewModel, you have a couple of options:
Include the Model as a property of the VM, and pass the model instance into the VM's constructor. You can then expose the Customer's properties and just wire them through to the underlying Model's corresponding properties.
Generate a ViewModel using T4 templates and Reflection (or preferably Introspection) to 'read' the Model, and generate the properties that will map directly to it.
Now you can add custom validation rules to the VM, such that when the appropriate command is sent from the View you can perform your business rules, and if appropriate you can update the Model using EF's API to persist those changes back to the database...