C#MVC动态创建视图模型

本文关键字:模型 视图 创建 动态 C#MVC | 更新日期: 2023-09-27 18:27:13

我第一次使用实体框架开发一个新的MVC4项目。我真的很喜欢能够使用代码优先的模型,并通过迁移来更新数据库。我希望只有一个地方可以更改我的模型(实体类),并且对它的更改(如新属性)不仅可以在迁移后反映在DB中,还可以反映在我的视图模型中。

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

例如,对于这样一个简单的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;
}

有人能提供什么建议吗?

C#MVC动态创建视图模型

我创建了动态MVC来实现这一点。

http://dynamicmvc.com

安装程序包dynamicmvc

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