2013-08-12 126 views
2

我正在开发一个新的MVC4项目首次使用实体框架。我非常喜欢能够使用代码优先模型,并通过迁移来更新数据库。我希望能够只有一个地方来改变我的模型(实体类)并对其进行更改,例如新属性不仅在迁移后的数据库中反映出来,而且在我的视图模型中也会反映出来。C#MVC动态创建视图模型

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

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

我想产生looke像这样的动态类:

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

任何人都可以提供任何advi CE?

+1

ViewModels的主要观点是,它们不是模型实体的重复...这似乎是一种自我挫败。 –

+0

我想用属性做更复杂的事情,以便它不会重复,但意味着我可以控制一个文件中的所有内容。 – user1573618

+0

您是否考虑过使用T4? – boindiil

回答

2

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

http://dynamicmvc.com

安装包dynamicmvc

这种方法的主要好处是它可以让你专注于自己的业务逻辑,并有简单的场景自动生成的UI逻辑。