C#MVC动态创建视图模型

时间:2013-08-12 06:47:33

标签: c# asp.net-mvc entity-framework dynamic

我是第一次使用Entity Framework开发一个新的MVC4项目。我真的希望能够使用代码优先模型并使用迁移更新数据库。我希望能够只有一个地方来更改我的模型(实体类)以及对此进行更改,例如新属性不仅要在迁移后的数据库中反映出来,还要反映在我的视图模型中。

所以,我想做的是能够使用我的实体类生成动态视图模型类。视图模型应该复制我的实体类中的所有属性和值,并在我的实体类属性中定义一些特殊逻辑。

例如,对于这样一个简单的enity框架模型:

public class UsersContext : DbContext
{
      public UsersContext()
          : base("DefaultConnection")
      {
      }

      public DbSet<UserProfile> UserProfiles { get; set; }

      [Table("UserProfile")]
      public class UserProfile
      {
          [Key]
          [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
          public int UserId { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }
       }
}

我想生成一个像这样的动态类:

public class UserProfileView
{
      [ScaffoldColumn(false)]
      public int UserId { get; set; }

      public string FirstName { get; set; }

      public string LastName { get; set; }
}

伪代码可能看起来像这样,但我不知道如何实现它:

function dynamic GeneraveViewModel(object entity)
{
    Type objectType = entity.GetType();
    dynamic viewModel = new System.Dynamic.ExpandoObject();

    //loop through the entity properties
    foreach (PropertyInfo propertyInfo in objectType.GetProperties())
    {
         //somehow assign the dynamic properties and values of the viewModel using the property info.

         //DO some additional stuff based on the attributes (e.g. if the entity property was [Key] make it [ScaffoldColumn(false)] in the viewModel.
     }

     return viewModel;
}

有人可以提供任何建议吗?

1 个答案:

答案 0 :(得分:2)

我创建了动态MVC来做到这一点。

http://dynamicmvc.com

Install-package dynamicmvc

这种方法的主要好处是它可以让您专注于您的业务逻辑,并为简单的场景自动构建UI逻辑。