Say I have one class
that looks like this:
public class Person
{
public string Name {get; set;}
public int Number {get; set;}
}
Install AutoMapper
package in your project.
As a best practice (for web applications) you can create new class (should derives from Profile
) in your App_Start
folder, that will contain all your mappings for your project.
namespace MyApp.App_Start
{
public class MyAppMapping : Profile
{
public MyAppMapping()
{
CreateMap();
//You can also create a reverse mapping
CreateMap();
/*You can also map claculated value for your destination.
Example: you want to append "d-" before the value that will be
mapped to Name property of the dog*/
CreateMap()
.ForMember(d => d.Days,
conf => conf.ResolveUsing(AppendDogName));
}
private static object AppendDogName(Person person)
{
return "d-" + person.Name;
}
}
}
Then Initialize your mapping inside the Application_Start
method in Global.asax
protected void Application_Start()
{
Mapper.Initialize(m => m.AddProfile());
}
You can now use the mappings that you have created
var dog = AutoMapper.Mapper.Map(person);