AutoMapper Custom Projections
mohamed tayel
Technical Project Lead @ SURE| Scrum Master | Technical Project Manager | .Net Technical Lead | .NET Instructor
AutoMapper projections in a simple way
Assume we have 2 classes
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Address Address { get; set; }
public string GetFullName()
{
return $"{LastName}, {FirstName}";
}
}
public class Address
{
public int Id { get; set; }
public string Door { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
}
And at the end, the destination object that will be shown in the UI:
public class UserViewModel
{
[Display(Name = "Full Name")]
public string FullName { get; set; }
[Display(Name = "Country")]
public string AddressCountry { get; set; }
public string Email { get; set; }
}
As you can see, in the current view model, we are applying one of the naming conventions for the automatic mapping by naming the property?AddressCountry. That means that the AutoMapper will search for a child object named?Address?and its property named?Country.