我第一次使用实体框架开发了一个新的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;
}有人能给点建议吗?
发布于 2014-09-10 12:50:48
我创建了Dynamic MVC来做这件事。
Install-package dynamicmvc
这种方法的主要好处是,它允许您专注于业务逻辑,并为简单的场景自动构建UI逻辑。
https://stackoverflow.com/questions/18181002
复制相似问题