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: http://share.linqpad.net/neu8bm.linq

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);
 cd.Dump();
}

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

No comments: