ASP.NET MVC ViewModel Auto Generation - asp.net-mvc

I have a load of ADO.NET Entities in my MVC project. I was going to use these entities directly from my views/controllers... however, I think it's probably best to use ViewModels which more accurately reflect what the View requires.
I'm looking for a way that I can auto-generate a ViewModel from an existing Entity, i.e., auto-generate the wrapper or adapter pattern from an existing member... Or a T4 template that would loop through the public properties of an Entity, and output properties for the ViewModel... then I can delete the properties I don't need or create aggregate view models etc.
I cannot seem to find anywhere a way to auto-gen a wrapper or adapter pattern class from an existing type?
The idea is then at runtime, use AutoMapper to map between the ViewModel and the Entity.
thanks

You could use AutoMapper to convert from your domain model to a view model. There's a great post from Jimmy Bogard explaining how you could integrate this within your controller actions.

http://weblogs.asp.net/rajbk/archive/2010/05/04/a-basic-t4-template-for-generating-model-metadata-in-asp-net-mvc2.aspx
That can help. It is actually for metadata generation for existing entity types. But you can use it to generate clean view models with data annotations as well. Maybe with a little modification.

Related

Are there Visual Studio Tools For Creating DTO/ViewModel

I'm trying to introduce ASP.Net MVC to my department. I am encouraging them to have a ViewModel per View and AutoMapper for our larger projects (and ideally in general).
Sometimes this means having one large entity and picking 5 of its properties and creating the ViewModel. This is done by looking at the the edmx model (many projects were existing so it was DB first) and then creating matching properties in a ViewModel class. Obviously names etc have to match for AutoMapper to work. Also for navigation properties you have to add the navigation name first. Ideally also being able to type in a display name etc.
I'm trying to ease them into doing this (what they see as extra work). Is there any tool that would load a list of fields and allow you to select via checkbox etc and create the class from that?
I guess the same would apply to DTOs etc
Thanks
Have you tried this http://www.codesmithtools.com/product/generator
you can create a template of the dto and then it will generate the files/dto's for you as needed from any kind of datasource.

Is it bad practice to use a lot of viewmodels in asp.net mvc

Been working on a pet project on the side to learn asp.net mvc better. My question is about viewmodels in mvc. I understand the controller is supposed to handle the interaction between the view and the model. I feel like I keep having to create viewmodel classes to combine information from the models to pass to the view.
Is this bad practice? Should I be doing more of the logic elsewhere and cut down on the viewmodels?
At the moment I've almost got a viewmodel for just about every one of my main views. But I definitely don't want the view to access the model directly.
No, all your views should be strongly typed, so using for each view one viewmodel is best practice. Here is very nice article about viewmodels.
The more viewmodels you use the better. The viewmodels allow you to create a single object that can contain different types of data from your models. These are very useful when creating templates. Also, this is very useful when using JQuery and Ajax since its a nice way to pass data into your controller and then directly to the DOM. In my opinion, use as many viewmodel as you desire.
Another thing that you might consider is to try to have better design of your model. I personally try to build my model just like a sql database and follow the normalization forms. You should not have to create a new viewmodel for each view in addition to the models you already have. If you need to pass information to the view that is not part of the model you are using, use ViewData or ViewBag. These are passed as an object so you will have to cast them to the appropriate class.
Nothing bad in this. As much your viewmodel closer to view as better.
Model could not particullary match View, so you use ViewModel class for that.
Great answers here, and here is my view on why a lot of view models are not an issue.
Your ViewModels are a nice way of separating your pure Data Access Objects or even your Domain Objects from your presentation layer and provide a dumbed down version of those objects for your views to consume.
Your views are supposed to be dumb and for me personally, what I try to achieve is to massage my domain model into a ViewModel for my view to consume.
Using lot of viewmodels creates mess in your project. It is much better to just create a Tuple in the controller then pass it.

How to create model quickly&elegantly with Linq To Sql in asp.net mvc?

Ok straight to the issue. I can get object mapping to tables easily with Linq To Sql. For instance: class Product, class Order, class Order_Detail from Northwind. IMO, these 3 object have already met model's meet. But i can't put some useful attr([Required] [HttpPost]) on properties of them(except modifying design.cs, which is not recommended).Do i have to create ProductModels OrderModels with the same properties myself, and maybe some additional DAL-like classes to turn the linq2sql objects to models??
EDIT:
Even if i put design.cs and my models in the same namespace, how can i make two partial classes have the same properties??
Yes, you should create DTO's for each Linq to SQL model, it is not considered a good practice to pass Linq2Sql objects through your layers.
Optionally, look into to using Entity Framework Code First. It is stupid simple to use and you can add validation attributes directly to your POCOs, which are enforced on the data persistence side as well as the presentation side in MVC.
here's a good EF codefirst primer : http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

Generate DataAnnotations with Fluent API and ObjectContext

I'm building an application using MVC 3 and Entity Framework 4.
I've created my Entity Data Model and generated a database from it.
Now I know the validation attributes such as [Required] or [StringLength(5)] can be used on the model properties to provide validation both clientside and serverside.
I would like to know if these attributes can also be generated dynamically instead of having to add them to the model explicitly? I saw that in EF 4.1 RC you can make use of the Fluent API to further configure your model in the OnModelCreating method by using the DbModelBuilder class.
As shown here
I'm working with a framework however that still uses ObjectContext instead of DbContext so I would like to know if the above solution can be used in combination with ObjectContext?
As a final note, since I've been trying to figure out how to generate and use data annotations it seems using view models would increase the complexity of validation. From what I read here it seems that just passing the models directly to the view would remove the need to add annotations to the models as well as the view models. However that means that you can no longer use strongly typed views when you do joins on the models and pass those to the view directly?
No it can't. Fluent API is different approach to describe mapping. You can use fluent API or EDMX (Entity Data Model). Not both. Fluent API also works only with DbContext API. If you want to have annotations generated you can try to modify T4 template generating your classes.
I have come across a disturbing issue when using poco classes that are extending base classes.
For example, let say you have a Person poco class that has a strongly typed Car property. You also have a Spouse poco that also uses the Car Property.
Now you want to display "Person Car" and "Spouses Car" in the view using the Display("Name = xxx") attribute. You cant!!! Becareful of this issue if you are not using flat View Models

MVC3 EF model-first with POCO and ViewModels

Lots of great posts out here on this topic and I've tried to read them all. I'm a long time n-tier developer but trying to swing into action with an MVC3/EF application. I've generated POCOs via the EF POCO generator(T4). I'm also binding ViewModels to my Views...no EF stuff in my Views. My question has to do with validation (U/I only). I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels. From the advice I see on this site and others, I'll have to replicate any properties from my POCOs into my view models and do my annotations there. To make this easier I've seen lots of suggestions to use AutoMapper to make this tedious mapping more bearable.
Do I pretty much have the right idea?
I'm also binding ViewModels to my Views...no EF stuff in my Views
Correct. Ideally, your POCO's should not be on your Views.
I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels
Correct. There shouldn't be any data annotations on your POCO's.
From the advice I see on this site and others, I'll have to replicate any properties from my POCOs into my view models and do my annotations there
Why? Are you always binding to all of the properties on your POCO's? Remember, the ViewModel is to serve the View only. So if you have a form to submit an order, the ViewModel should only contain what is required to persist that Order. A combination of AutoMapper and your custom code can then map that to your POCO.
To make this easier I've seen lots of suggestions to use AutoMapper to make this tedious mapping more bearable
#Craig is right, it has nothing to do with Data Annotations. AutoMapper maps your ViewModel to your domain models with a few lines of configuration.
AutoMapper is only about transformation from entity to view model and vice versa. It is just replacement of code like custom conversion operator between types. You will still have to create your view models and mark properties with correct data annotations.

Resources