Tuesday, April 28, 2015

Auto mapper to map domain object gracefully in .NET

In application development, we often implementing mapping between DTO object and ViewModel object if it is MVC application. We know that DTO model is very similar to table stricture where ViewModel is very much similar to user interface.

Now, Question is that how we can map two different objects. The straightforward way to implement mapping is just to map property to property. Using AutoMapper we can make it little bit smart.
To use auto mapper we have to get reference of AutoMapper.NET4 assembly which we can get from NuGet package manager.
So, let’s implement AutoMapper in one sample application. Here is the implementation of person and Address class.

class person
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Address Address { get; set; }

    class Address
        public string State { get; set; }
        public string Cuntry { get; set; }

Please have a look that “Address” member of person class is type of Address class. Now, the simplest view model to get full information of person is like this.

class personViewModel
        public string FullName { get; set; }
        public Address Address { get; set; }

Here, we will write few lines of code to map two objects.

public ActionResult Index()
            var person = new person { FirstName = "Sourav", LastName = "Kayal", Address = new Address { State = "WB", Cuntry = "IN" } };
            personViewModel personVM = new personViewModel();

                ForMember(f=>f.FullName , f=>f.MapFrom(a=>a.FirstName + a.LastName));

            var data = Mapper.Map<person, personViewModel>(person);

            return View();

Here we are seeing that Full name is the combination of both FirstName and LastName. 

And Address property has mapped automatically.

No comments:

Post a Comment