Saturday 10 August 2013

Models in Asp.net MVC should be called ViewModels , why ?

By default ( default template of asp.net mvc ) Models in mvc architecture are used in two senses i.e. one is as POCO entities which represents the entities of our system and other is as containers which are filled in controllers and bring data back to views as we declare model at the top of each strongly typed view.

 @model Base.Models.QueryModels

In professional way these are two different things lets say we are using entity frame work ( database first approach using .edmx ) , we know that it provides one DbContext object and by instantiating we can get our entities and their crud operations which in returns gives us results as objects ( a presentation of database table) and that objects are our entities. Lets say at that time we are standing in our controller , we have database results fetched in an object and we just need to pass them in our View( ) , that is the point where we use our ViewModels.

For one entity we can have multiple ViewModels and why is that so because of view requirements , a customer role can have a different view than an Administrator etc , now the question is this what is an appropriate way to translate our entities to ViewModels , we can do this in two way :

1 ) Create custom mapping extension e.g. lets say we have an entity User.cs and a view model      UserModel.cs as given bellow:

public class User
{
   [Key]
   public virtual int UserId { get;set;}
   public virtual string FirstName { get;set;}
}

public class UserModel
{
   public int Id { get;set;}
   public string Name {get;set;}
}

Now in order to map them we can create our custom mapping in a separate class :

 #region user

        public static UserToEntity(this UserModel model)
        {
            var entity = new User()
            {
             
                UserId= model.Id,
                FirstName=model.Name,

            };
            return entity;
        }

        public static UserModel ToModel(this User entity)
        {
            var model = new UserModel()
            {
               Id=entity.UserId,
                Name= entity.FirstName,
            };
            return model;
        }

        #endregion

And to use this in controller just call ToModel with your entity:

   public ActionResult Details(int id)
        {
            var user= from users in db.Users where users.Id==id
                           select users;

            return View(user.ToModel()); // here entity is converted to your view model
        }

2 ) Second way is to use third party to map your models and entities with each and other , auto-mapper is good for that task.


That was all about how we can separate our models form entities , why we do that and its advantages, in next post hopefully I will demonstrate how to use Automapper to do model and entity mappings.

No comments:

Post a Comment