Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC ViewModel Auto Generation

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

like image 368
krisdyson Avatar asked Apr 19 '10 09:04

krisdyson


2 Answers

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.

like image 53
Darin Dimitrov Avatar answered Nov 15 '22 06:11

Darin Dimitrov


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.

like image 27
Serguzest Avatar answered Nov 15 '22 05:11

Serguzest