Can I just enhance the Model instead of building a ViewModel? - mvvm

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

Related

Conditional Validation on MVC3 Model Class

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.

ZF models correct use

I am struggling with how to understand the correct usage of models. Currently i use the inheritance of Db_Table directly and declare all the business logic there. I know it's not correct way to do this.
One solution would be to use Doctrine ORM, but this requires learning curve and all the current components what i use needs to be rewritten paginator and auth. Also Doctrine1 adds a another dozen classes which need to be loaded.
So the current cleanest implementation what i have seen is to use the Data Mapper classes between the so called model and DbTabel. I haven't yet implemented this as it seems to head writing another ORM. But example could be something this: SQL table User
create class with setters, getters, business logic here /model/User.php
data mapper /model/mapper/UserMapper.php, the funcionality is basically writing all the update, save actions in here.
the data source /model/DbTable/User.php extends the Db_Table_Abstract
Problems are with relationships between other models.
I have found it beneficial to not have my models extend Db_Table, but to use composition instead. That means my model 'has a' Db_Table rather than 'is a' Db_Table.
That way I find it much easier to reference multiple tables in the same model, which is a common requirement. This is enough for a simple project. I am currently developing a more complex application and have used the Data Mapper pattern and have found that it has simplified my code more than I would have believed.
Specifically, I have created a class which provides all access to the database and exposes methods such as getUser() etc.. That way, if the DB changes, or my client wants something daft like storing records in XML or we split the servers or something I only have to rewrite one class.
Again, my models do not extend this class, but have an instance of it assigned as a property during construction.
I would say the 'correct' way depends on the situation. Following the YAGNI and KISS principles, it is not good to over-complicate your model setup unless you really believe that it will benefit you in the long run.
What is the application you are developing? How is your current setup of extending Db_Table holding you back?

Where should ASP.NET MVC 2 validation go: in the model or viewmodel classes?

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

Model responsibilities in MVVM

Is Model only Entity Data Model class of my database? Model as simple place where i have my data? Or I can input in Model something more?
The model in MVVM is supposed to be the place for data-centric logic and the data, yes. It can be just the Entity Data Model, or you can add some more logic--that's up to you. The primary point is to seperate any presentation-specific logic from the model and put that in the viewmodel.
Hope that's clear enough
You can do whatever you like...
Typically, though, the "model" in MVVM is considered to be an "external" class (e.g. a generated class from LINQ-to-Entities, say) and so it usually doesn't have much logic.
The model is the core domain logic you are dealing with. It is everything not directly related to a UI view.
An easy way to think of it is the View and ViewModel combined represent what would be a "typical" UI layer without good separation. In MVVM, you split the logical aspects (the ViewModel) from the display logic (the View).

How to get Entity Framework and MVVM to play nicely together?

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...