ASP.NET MVC ViewModel自动生成

时间:2021-01-27 03:27:11

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.

我的MVC项目中有大量的ADO.NET实体。我将直接从我的视图/控制器中使用这些实体...但是,我认为最好使用ViewModel,它可以更准确地反映View所需的内容。

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.

我正在寻找一种方法,我可以从现有实体自动生成ViewModel,即从现有成员自动生成包装器或适配器模式...或者循环通过公共属性的T4模板ViewModel的实体和输出属性...然后我可以删除我不需要的属性或创建聚合视图模型等。

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.

然后在运行时使用AutoMapper在ViewModel和Entity之间进行映射。

thanks

2 个解决方案

#1


2  

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.

您可以使用AutoMapper将域模型转换为视图模型。吉米·博加德(Jimmy Bogard)发表了一篇很棒的文章,解释了如何将其整合到你的控制器动作中。

#2


1  

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.

这可以帮助。它实际上是用于现有实体类型的元数据生成。但您也可以使用它来生成带有数据注释的干净视图模型。也许稍作修改。

#1


2  

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.

您可以使用AutoMapper将域模型转换为视图模型。吉米·博加德(Jimmy Bogard)发表了一篇很棒的文章,解释了如何将其整合到你的控制器动作中。

#2


1  

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.

这可以帮助。它实际上是用于现有实体类型的元数据生成。但您也可以使用它来生成带有数据注释的干净视图模型。也许稍作修改。