user1573618
user1573618

Reputation: 1816

C# MVC Dynamically create view model

I am developing a new MVC4 project using Entity Framework for the first time. I really like being able to use code first models and update the database with migrations. I would like to be able to just have one place to change my model (the entity class) and for changes to this such as new properties to be reflected not only in the DB after a migration, but also in my view models.

So, what I would like to do, is to be able to generate a dynamic view model class using my entity class. The view model should copy all the properties and values from my entity class with some special logic defined in my entity class attributes.

For example, for a simple enity framework model like this:

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

I would like to generate a dynamic class that looke like this:

public class UserProfileView
{
      [ScaffoldColumn(false)]
      public int UserId { get; set; }

      public string FirstName { get; set; }

      public string LastName { get; set; }
}

The pseudo code could look something like this but I don't know how I can achieve it:

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

Can anyone offer any advice?

Upvotes: 3

Views: 7570

Answers (1)

Chris Perry
Chris Perry

Reputation: 121

I created Dynamic MVC to do this.

http://dynamicmvc.com

Install-package dynamicmvc

The main benefit to this approach is it allows you to focus on your business logic and have the UI logic built automatically for simple scenarios.

Upvotes: 2

Related Questions