CRUD Opearations using AutoMapper

0

Category :

Challenge

Sometimes while interacting with real time (database) entities and binding our model to them, we end up in a situation like:

var dbContext = new MyDBDataContext();
var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
var user = new LearningMVC.Models.User();
if (userDetails != null)
{
    user.UserId = userDetails.UserId;
    user.FirstName = userDetails.FirstName;
    user.LastName = userDetails.LastName;
    user.Address = userDetails.Address;
    user.PhoneNo = userDetails.PhoneNo;
    user.EMail = userDetails.EMail;
    user.Company = userDetails.Company;
    user.Designation = userDetails.Designation;
}
return View(user);
We have an existing model named User (LearningMVC.Models.User()) that has similar properties as that of the Users class generated from the database. Now we initialize properties of the instance of our model from properties of instance of the User class from the database so that we can populate our View in an MVC application.

Now the problem is what if we have 100 column records coming from the database, and also our model has the same number of properties, and the code has to be repeated 6-7 times at different scenarios?

Auto Mapper

As per the AutoMapper CodePlex webpage: "AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper's established conventions, almost zero configuration is needed to map two types." Therefore, it provides the solution for our mapping issue.

Example

public ActionResult Index()
{
    var dbContext = new MyDBDataContext();
    var userList = from user in dbContext.Users select user;
    var users = new List();
    if (userList.Any())
    {
        foreach (var user in userList)
        {
            users.Add(new LearningMVC.Models.User()
                {
                    UserId = user.UserId, 
                    Address = user.Address, 
                    Company = user.Company, 
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Designation = user.Designation,
                    EMail = user.EMail, 
                    PhoneNo = user.PhoneNo
                });
        }
    }
  
    return View(users);
}
To create the default mapping, call Mapper.CreateMap() with proper types. In this case, T1 will be LearningMVC.User and T2 will be LearningMVC.Models.User.

Mapper.CreateMap();
Now inside the foreach loop, replace the whole code by:
LearningMVC.Models.User userModel = Mapper.Map(user);
users.Add(userModel);
So, our final Action code:
public ActionResult Index()
{
    Mapper.CreateMap();
    var dbContext = new MyDBDataContext();
    var userList = from user in dbContext.Users select user;
    var users = new List();
    if (userList.Any())
    {
        foreach (var user in userList)
        {
            LearningMVC.Models.User userModel = 
              Mapper.Map(user);
            users.Add(userModel);
        }
    }
    return View(users);
}

ForMember() and MapFrom() in AutoMapper

Two important functions in AutoMapper play an important role in object mapping. Suppose our model/viewmodel class has a property FullName, and from the DTO we want to add the First Name and Last Name of the user to make it a full name and bind it to the model. For these kinds of scenarios ForMember() and MapFrom() come in handy.

Mapper.CreateMap().ForMember(emp => emp.Fullname,
map => map.MapFrom(p => p.FirstName + " " + p.LastName));
Here we are saying that ForMember FullName in our model class maps properties from FirstName and LastName of User DTO.

my thanks to: http://www.codeproject.com/Articles/639618/CRUD-Opearations-using-AutoMapper-in-an-MVC-Applic

0 comments:

Post a Comment