What to do when Model is exactly the same as ViewModel? - c#

I want to know what is best practice. I have been told to always create ViewModels and never use core Model classes for passing data to Views.
That makes sense.
Lets me separate the things out. But what is Model is exactly the same as ViewModel. Should I recreate another class or just use it.
I feel that I should recreate. Just want to know what the experts say..

You should definitely still create a separate view model, even if it is identical to your domain entity. The view model and the domain entity should be completely independent, i.e. you should be able to change one without the other needing to know or care about the change. Your view model should represent your view and your domain entity should... well... represent your domain entity. They might be identical now but, if either changes, the change in one should not affect the other.
What if your domain model suddenly changes and now has fields that are no longer relevant to your view model? If they aren't separate, you have a problem. Or, worse (and probably more likely), what if your view model suddenly needs more information, from a totally distinct entity? Are you going to break the encapsulation of classes in your domain model with this totally irrelevant information, just to make it accessible in your view?
Keep your solution decoupled and flexible. Use view models.

I would suggest to create a ModelView, by the way. So in this, particular case it would be the same, it would work like a "bridge" between UI and a model, on which data trasmittes.
But it's good for scallability, cause, it's very likely that you would like to add something UI specific to your view model, so it will defer from the model itself more and more.
So general advice: create it by the way, even if now they are the same, cause it helps you scale when you will need it after.

But what is Model is exactly the same as ViewModel. Should I recreate
another class or just use it.
If it's exactly the same you don't need a view model of course. But that is a pretty rare situation.

Related

.NET MVC data binding methods

I realize this doesn't necessarily apply to MVC exclusively, but bear with me.
Working with entity framework and models, I've read several articles on "best practices" where some people claim using repositories and unit of work is better, others claim it's overkill and using your models directly within your controllers with linq is better, so on and so forth...
Then we have view-models and lazy loading methods, but then with linq we can use joins to add multiple "models" to our data retrieval to fetch whatever we need directly in our controller or helper class.
I realize a lot of this ties back to the "separation of concerns" that is MVC and we can create multiple layers to map our data back whichever way we want, which is great, but let's say for argument sake my app run exclusively on MS SQL, with no chance of ever transitioning to another database type, will adding all the additional layers of separation to map data back give me any real benefit? I'm just trying to understand at which point does one conclude it's better to do it this way over that way? I know some of this might consist of personal preference, but I'm looking for REAL LIFE scenarios where it's easy for me to conclude one way it better than the other AND what questions I should ask myself when deciding how many mapping layers do I need to get my data from my database to my view?
One of the real benefits is when your models or your UI need to change independently of each other. If your view is only tied to a ViewModel instead of your entity, then you can make all of the mapping changes in one place (your controller) instead of needing to go through every view that your entity is being used and making changes there. Also, with ViewModels, you have the benefit of combining multiple data sources into a single object. Basically, you get a lot more flexibility in how to implement your UI if you don't tie it directly to database tables.

Benefits of strictly separating View and Model?

A colleague of mine doesn't want to bind from the View directly to the Model. For example, in the Model, he has a ObservableCollection and in the View he wants to use it. Instead of directly using it like I would do it (e.g. {Binding Model.Collection} he has another ObservableCollection in the ViewModel which has exactly the same data as the ObservableCollection in the Model. He is synchronizing both ObservableCollections with each other through events.
What are the benefits of his approach? I, personally, disapprove of his approach because it just adds duplicate code and since you have to synchronize the ObservableCollections yourself it's also more error prone. My colleague says he wants to do it this way because then he can change the Model without changing the View.
EDIT:
Some highly upvoted answers [1][2][3] support my in my thinking that it's really okay to bind directly to the Model.
It all comes down to code separation and reusability. Ideally, the View should be completely separated from the Model. If the View doesn’t rely on a specific implementation of the Model, then it can be reused with a different model to present some other data.
So, suppose you have a AlbumView and your current Model is Album, but in future you have decided to also add Movie or Book to you library. you could still use the same AlbumViewo display your movie and book objects. Furthermore, if you want to create a new project that has something to do with albums, you could simply reuse your Album class, because it’s not dependent on any view. That’s the strength of MVVM or MVC.
So for me, I would say, that your colleague is right, because Model naturally reflect the Data Access Layer Entity, where it will be stored and handled. In addition to that, Model may have more properties related to Access data layer such as created indexing. While you ViewModel is only related to the view and the presentation logic of your application. It only reflect what the user is going to see.
I would say using an ObservableCollection in the Model layer is wrong. By adding that you are basically saying "Model object stores data and notifies when it changes".
The role of the ViewModel is to manipulate the Model and provide an interface to the View for presenting the Model.
I believe your colleague is right because he is enforcing separation of concerns such that manipulating the Model should not impact the View.

What to do when data from the service layer needs to be shared between different presentation entitites

first of all, please forgive me if I get the terminology wrong. Terminology is important, but similar concepts are often expressed with different terms.
Let's say I have two, not well defined, "entities" in my presentation layer that must use the same data retrieved from the Service layer. What does entities should be?
Should these entities be both presenters of MVPs? If so, does it make sense to create two MVP triads that handles somehow the same data (but of course in a different way)?
Is it perhaps better to have one presenter and multiple views?
Or maybe it means that the Model is too bloated and it should be split into different models?
Although I am sure there is a design issue somewhere in our code, I noticed that we have several classes, that cannot even be defined as presenters, using independently the same data from the service layer and this bothers me a lot.
In MVP, the Presenter is tighly coupled to each View (since it controls the behaviour of the View). That means if you have multiple Views that differ substantially, then you need to have also multiple Presenters.
But neither the View nor the Presenter hold any data. The Model is the representation of the current state of the data in the application.
So if the data you fetch from the service layer is handled in the same way for both cases (but just presented differently), then you should have one Model which is referenced by both Presenters.
But if what you fetch is just some kind of "raw" data which gets processed in a very different way, then you probably should also create an own Model for each Presenter/View. The model can reference the fetched data which can be held somewhere in the Service layer or a higher level model object.

Dal (with Entity Framework) and Model layers into MVC

First of all , I use EF into Dal layer (separeted project from MVC, same solution). The generated models from EF's EDMX file are the actual models from Model layer?? If so, how do I access these models to work in MVC's View layer? I think it's wrong accessing data layer directly from view to work with these models, and If I make a Model layer with "my models" and translate Dal's models into mine models... it'll be duplicated code.
Probably I'm getting something wrong, but most of egs. are with code first approach, and I can't figure out this.
You are right in your idea of not accessing access the Models in your DAL directly from your presentation layer.
To avoid duplicating code when translating your DAL objects into the Models used by your views, you could use something like AutoMapper, which is supposed to do the heavylifting for you in exactly that scenario.
I think it's wrong accessing data layer directly from view to work with these models...
That's right, the appropriate method is using View Model
When you have dozens of distinct values to pass to a view, the same flexibility that allows you to
quickly add a new entry, or rename an existing one, becomes your worst enemy .You are left on your
own to track item names and values; you get no help from Microsoft IntelliSense and compilers .
The only proven way to deal with complexity in software is through appropriate design. So defining an object model for each view helps you track what that view really needs. I suggest you define a
view-model class for each view you add to the application.
-- "Programming Microsoft ASP.NET MVC" by Dino Esposito
A ViewModel provides all information that your view requires to make itself. To transfer data from ViewModel and a business entity you can use AutoMapper.
Don't worry about duplication, those are two different concept and should be separated from each other; it makes your application easy to maintain.
I may be mistaking but to me, using generation from EDMX provides you with the DbContext which could be considered as the DAL and entities which could be considered as the Model.
So you might directly manipulate entity instances as your business object. Manipulation of the base through the DbContext should appear in the BLL layer. Additionally, you might implement DTOs where needed.
This, of course, assumes you want to use entity framework code generation. Other options like using POCOs might be more relevant considering your overall architecture.
I use a view model in my local project and the models in the other project. Then put references to the models im gonna use on the page in my view model. Then reference the view model on my page. Let me know if that sounds like something you want to do and I can edit in some code.

Should I use AutoMapper from ViewModel to Model objects

I want to go the way doing all input validation in a viewmodel.
When the database is accessed the viewmodels data must be copied over to the model sent to database.
My concern is that data could be lost because:
Automapper is wrongly setup for certain scenarios thus properties are not copied over to the model
Or Automapper is just not suited for every scenario maybe too complex ViewModels
Are my concerns justified or should I not care for that?
Automapper is totally fine in this scenario I use it extensively for exactly this purpose. If you are worried about data lose should you not be making use of data annotation validation on the model itself to make sure you have the required data before persisting or calling some other service.
Also the only real way to make completely sure that you dont miss anything using Auotomapper or just manual code mapping is a good set of unit tests.
My concern is that data could be lost because: Automapper is
wrongly setup for certain scenarios thus properties are not copied
over to the model Or Automapper is just not suited for every scenario
maybe too complex ViewModels
I think it is unlikely that you will loose data. For complex
viewModels you can choose to set specific properties manually which
are not copied over by Automapper. As suggested by #feanz good Unit
Test will provide you required assurance.**

Categories