【问题标题】:C# MVC Dynamically create view modelC# MVC 动态创建视图模型
【发布时间】:2013-08-12 06:47:33
【问题描述】:

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

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

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

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;
}

谁能给点建议?

【问题讨论】:

  • ViewModel 的主要观点是它们不是模型实体的复制品...这似乎有点自欺欺人。
  • 我想用属性做更复杂的事情,这样它就不会重复,但这意味着我可以从一个文件中控制一切。
  • 你考虑过T4的使用吗?
  • 我什至从未听说过它,但它看起来很有前途(对于像我这样不知道的任何未来读者来说,它是 T4 文本模板)。
  • 使用 T4,您可以为 ViewModel 创建部分类,在单独的文件中添加您的附加逻辑,还可以使用 AutoMapper 映射对象类型

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


【解决方案1】:

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

http://dynamicmvc.com

安装包dynamicmvc

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多