Models;
public class Customer
{
public string Name{ get; set;}
public string Surname{ get; set;}
public int ID{ get; set;}
}
public class Person
{
public string FullName{ get; set;}
public int Age { get; set; }
}
Auto Mapper Class;
public class CustomerToPersonConverter:ITypeConverter<Customer,Person>
{
public Person Convert(ResolutionContext context)
{
Person person = new Person();
Customer customer = context.SourceValue as Customer;
person.Age = customer.ID + 15;
person.FullName = customer.Name + " " + customer.Surname;
return person;
}
}
In Page_Load;
protected void Page_Load(object sender, EventArgs e)
{
Customer customer = new Customer()
{
ID=1,
Name="Engin",
Surname="Dotnet"
};
//Set The Map - #1
Mapper.CreateMap<Customer, Person>().ForMember(per => per.FullName, mus => mus.MapFrom(opt => opt.Name + " " + opt.Surname)).ForMember(per => per.Age, mus => mus.MapFrom(opt => opt.ID + 14));
//Set The Map - #2
Mapper.CreateMap<Customer, Person>().ConvertUsing<CustomerToPersonConverter>();
//Set The Map - #3
Mapper.CreateMap<Customer, Person>().ConvertUsing(cus =>
{
Person per = new Person();
per.Age = customer.ID + 15;
per.FullName = cus.Name + " " + cus.Surname;
return per;
});
///Then Use
Person person = Mapper.Map<Customer, Person>(customer);
Response.Write(person.Age + " " + person.FullName);
}
No comments:
Post a Comment