Thursday, March 30, 2017

Automapper in action

Automapper is an object to object mapper which takes can help you eliminate the yak shaving step of mapping your datastore object model to your view model.

I put together a demo because I believe it when I see it in action.

Here's a working LinqPad version here:

Or see the code online here...

Nuget package to install: AutoMapper
using Automapper //import namespace
void Main()
 //This converts a normalized contact object (cn) into a denormalized one (cd)
 var cn = new ContactNormalized
  FirstName = "Billy",
  LastName = "Bob",
  Hobby = "Jogging",
  Address = new Address { Line1 = "21 Elm Streer", Line2 = "C/O Mr. Giggles" }

 Mapper.Initialize(cfg => cfg.CreateMap()
   .ForMember(to => to.FullName, opt => opt.ResolveUsing(from=> "Mr. " +  from.FirstName + " " + from.LastName )) 

 ContactDenormalized cd = Mapper.Map(cn);

class ContactNormalized
 public string FirstName { get; set;}
 public string LastName { get; set;}
 public string Hobby { get; set; }
 public Address Address { get; set;}

class Address
 public string Line1 { get; set;}
 public string Line2 { get; set;}
 public string City { get; set;}
 public string State { get; set;}
 public string Zip { get; set;}

class ContactDenormalized
 public string FullName { get; set; }
 public string AddressLine1 { get; set; }
 public string AddressLine2 { get; set;}
 public string Hobby { get; set; }

1 comment:

Coepd BA Trainings said...

We at Coepd declared Data Science Internship Programs (Self sponsored) for professionals who want to have hands on experience. We are providing this program in alliance with IT Companies in COEPD Hyderabad premises. This program is dedicated to our unwavering participants predominantly acknowledging and appreciating the fact that they are on the path of making a career in Data Science discipline. This internship is designed to ensure that in addition to gaining the requisite theoretical knowledge, the readers gain sufficient hands-on practice and practical know-how to master the nitty-gritty of the Data Science profession. More than a training institute, COEPD today stands differentiated as a mission to help you "Build your dream career" - COEPD way.