2013-08-12 124 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邏輯。