I have a user entity in my application where users input some basic information when they register to the application. If they want to use some advanced features they have to give full information.
So I have two validation scenarios.
My first approach was to exchange the Required attribute with MyRequired attribute to avoid columns being created as NOT NULL in the database via Entity Framework.
But the model is validated if I add it to my DB context. So I can't add the entity if it's just filled with basic information.
Is there a way to have one entity with several different validation scenarios?
Is there any way to validate a model with different scenarious?
That's what view models are supposed to do. I would recommend you to avoid passing your EF models to the views. Also avoid passing EF domain models to your actions => always use view models. Those classes are specifically designed to meet the requirements of a given view, including validation attributes. Then map your model entities to your view models.
This way your domain models are completely decoupled from the way the information is being presented on a given view. Also (as it is your case) the same domain model could have two different representations on different views as well as different validation requirements of course => view models fill this gap.
Related
Is there any good reasons to create ViewModel that copy`s Model with addition of validation logic?
Why not simply extend current model with validation logic?
If you will create ViewModel copy, you need to
Create class with corresponding fields (which is not big problem if you have few models to validate, but what if you have many..)
Set automapper, wich can be slow, and adds additional logic to your solution (or do it by hand, which is probably, bad idea)
Support Model changes for ViewModel
These problems dissapear if you simply extend your basic Model. So why it is so popular to create ViewModel layer?
You can have two views with different validation logic for the same model.
the classic example is a sign up form, with a single page form vs a multi page wizard.
In both cases the model is the same, but in the wizard view its legitimate to submit the model half filled in, while the single page version should have all the fields validated.
Taking this possibility further leads to the one viewmodel per view methodology. Where you always make a viewmodel for a view as a matter of course because you expect to need the flexibility that it offers as a general thing.
Additionally, its pretty rare that view exactly matches a model. You usually require more than one model plus some odd extra bits. eg user model for the 'logged in as' header, list of models to display plus pagination info.
You can avoid some of the issues you mention by using ViewModels which simply wrap models and expose their properties where extra logic isn't required
I have read online that it is bad practice to use a "kitchen sink" model:
Rule #3 – The View dictates the design of the ViewModel. Only what is
required to render a View is passed in with the ViewModel.
If a Customer object has fifty properties, but one component only
shows their name, then we create a custom ViewModel type with only
those two properties.
Jimmy Bogard's subsequent explanation of how this is good, however, left me a little questioning. It'd be so easy to have my Model just contain a list of Customers, I could even use my POCO's.
So now I get to create custom little view model fragments for every page on the site? Every page that uses a Customer property would get one, but of course could not be shared since some of the information is extraneous, if one page used Age but not Name, for example. Two new mini view model classes right?
This is very time consuming, and seems like it'll lead to a million little custom view models - can someone elaborate as to the utility of this approach and why the easier approach is bad?
View model class can be used not only to transfer values, but it also defines data types (data annotations), validation rules and relations different then ones used in model. Some advantages that come to my mind right now:
There are different validation rules when you change user's password,
change his basic data or his subscription setting. It can be
complicated to define all these rules in one model class. It looks
much better and cleaner when different view models are used.
Using view model can also give you performance advantages. If you
want to display user list, you can define view model with id and name
only and use index to retrieve it from database. If you retrieved
whole objects and pass it to view, you transfer more data from
database than you need to.
You can define display, and editor templates for view models and reuse them on different pages using html helpers. It looks much worse, when you define templates for model POCOs.
If you would use your POCO objects as view models, you would essentially be showing your private objects and break the encapsulation. This in turn would make your model hard to change without altering the corresponding views.
Your data objects may contain details that are appropriate only to the data access layer. If you expose those things to the view, someone might alter those values that you did not expect to be altered and cause bugs.
Many of the same reasons as for having private members in OO languages apply to this reasoning. That being said, it's still very often broken because it's a lot of extra work to create all these "throw-away" models that only gets used once. There exists frameworks for creating these sorts of models, though the name eludes me, that can tie objects together and pick out the interesting properties only which takes away some of the drudgery from creating specific view models.
Your View Model tells the View how data should be shown. It expresses the model. I don't think its necessary to have two view models unless you have two ways to express your model. Just because you have two pages, doesn't mean you will be showing the data any different way, so I wouldn't waste time making two mini View Models when it can be in one reusable view model, Imagine if later you have a page that needs Name and Age, you would create another view model? It's absolutely silly. However, if you had two pages both showing 'Age' and it needed to be shown in a different way, then I would create another one.
My latest project involves actions returning different views at runtime (simply put, the application has a number of different customers as users, and they want their own custom data entry form designs - these forms all share the same model object-graph, but their display of the model's data is radically different to each other)...
For example, a "Case" entity has multiple People associated with it. Some forms only display a single Person's fields, other forms support multiple Persons, and another doesn't contain Person information at all. Furthermore, the forms have differing levels of fields - many forms lack many fields that others have.
Because of this radically different behaviour, I believe I'll need a different model binder for each view design.
Can StackOverflow recommend a course of action to take in this case, or an alternative solution that keeps the code simple.
If all your view models derive from a common abstract base view model you could have your POST action take this common view model as parameter and then write a custom model binder which will instantiate and bind the correct instance assuming each view sends an additional parameter containing the concrete type.
Here's an example of how this could be done.
I am using ASP.NET MVC 3 and I am using FluentValidation to validate my view models. I am just a little concerned that I might not be on the correct track. As far as what I know, model validation should be done on the domain object. Now with MVC you might have multiple view models that are similar that needs validation. What happens if a property from a domain object occurs in more than one view model? Now you are validating the same property twice, and they might not even be in sync. So if I have a User domain object then I would like to do validation on this object. Now what happens if I have UserAViewModel and UserBViewModel, so now it is multiple validations that needs to be done.
In my News class I have a property called Title, which is a required field. On my view model I also have a Title property, I use AutoMapper to map the News and NewsViewModel. So this validation is happening twice. When does domain model validation occur and when does view model validation occur?
The scenario above is just an example, so please don't critise on it.
It's a subtle distinction but the validation on your view model is to validate correct user input and forms an anti-corruption layer for your domain model, whereas the "validation" on your domain model enforces business rules. It is perfectly normal and you should have validation on both layers. In fact it may be feasible that UserAViewModel has slightly different input validation from UserBViewModel. As for your question, generally I try to avoid exposing domain objects through my ViewModel and instead map between them (often using something like AutoMapper), that way your ViewModels truly are anticorruption layers rather than property bags of domain models. Hope that helps.
What happens if a property from a
domain object occurs in more than one
view model?
This shouldn't happen. View models should be totally divorced from your domain.
Does this answer your question?
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
ASP.NET MVC - Linq to Entities model as the ViewModel - is this good practice?
Is is OK to use EF entities classes as view models in ASP.NET MVC?
What if viewmodel is 90% the same of EF entity class?
Let's say I have a Survey class in Entity Framework model. It 90% matches data required for view to edit it.
The only difference from what view model should have - is one or several properties to be used in it (that are required to populate Survey object because EF class cannot be directly mapped onto how it's properties are represented (sub-checkboxes, radio groups, etc.))
Do you pass them using ViewData[]? Or create a copy of Survey class (SurveyViewModel) with new additional properties (it should be able to copy data from Survey and back to it)?
Edit:
I'm also trying to avoid using Survey as SurveyViewModel property. It will look strange when some Survey properties are updated using UpdateModel or with default binder, while others (that cannot be directly mapped to entity) - using SurveViewModel custom properties in controller.
I like using Jimmy Bogard's approach of always having a 1:1 relationship between a view and a view model. In other words, I would not use my domain models (in this case your EF entities) as view models. If you feel like you are doing a lot of work mapping between the two, you could use something like AutoMapper to do the work for you.
Some people don't like passing these model classes all the way through to the view, especially as they are classes that are tied to the particular ORM you're currently using. This does mean that you're tightly binding your data framework to your view types.
However, I have done this in several simple MVC apps, using the EF entity type as the Model for some strongly-typed views - it works fine and is very simple. Sometimes simple wins, otherwise you may find yourself putting a lot of effort and code into copying values between near-identical Model types in an app where realistically you'll never move away from EF.
You should always have view models even if they are 1:1. There are practical reasons rather than database layer coupling which I'll focus on.
The problem with domain, entity framework, nhibernate or linq 2 sql models as your view classes is you cannot handle contextual validation well. For example given a user class:
When a person signs up on your site they get a User screen, you then:
Validate Name
Validate Email
Validate Password Exists
When an admin edits a user's name they get a User screen, you then:
Validate Name
Validate Email
Now expose contextual validation via FluentValidation, DataAnnotations Attributes, or even custom IsValid() methods on business classes and validate just Name and Email changes. You can't. You need to represent different contexts as different view models because validation on those models changes depending on the screen representation.
Previously in MVC 1 you could get around this by simple not posting fields you didn't want validated. In MVC 2 this has changed and now every part of a model gets validated, posted or not.
Robert Harvey pointed out another good point. How does your user Entity Framework display a screen and validate double password matching?
On bigger projects, I usually split up business objects from data objects as a matter of style. It's a much easier way to let the program and database both change and only affect the control (or VM) layer.