Created
May 13, 2017 14:30
-
-
Save lockedscope/6d9ed9b9e61edf45bfed11585cadda82 to your computer and use it in GitHub Desktop.
AutoMapper ResolveUsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Customer | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public string SurName { get; set; } | |
public DateTime DateOfBirth { get; set; } | |
public string HighSchool { get; set; } | |
public string University { get; set; } | |
} | |
public class CustomerDto | |
{ | |
public string FullName { get; set; } | |
public DateTime DateOfBirth { get; set; } | |
public Dictionary<string, string> Schools; | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Mapper.Initialize(cfg => | |
{ | |
cfg.CreateMap<Customer, CustomerDto>() | |
.ForMember(d => d.FullName, | |
opts => | |
opts.ResolveUsing( | |
(src, dest, destMember, resContext) => | |
resContext.Items["FullName"])) | |
.ForMember(d => d.Schools, | |
opts => | |
opts.ResolveUsing( | |
(src, dest, destMember, resContext) => | |
(Dictionary<string, string>)resContext.Items["Schools"])) | |
//resContext.Items["Schools"])) // Comment above line and Uncomment this line. | |
.ForMember(d => d.DateOfBirth, opts => opts.MapFrom(c => c.DateOfBirth)); | |
}); | |
var customer = new Customer { Name = "George", SurName = "Fanshaw", DateOfBirth = DateTime.Now.Subtract(TimeSpan.FromDays(365 * 30)), HighSchool = "The Salisbury School", University = "Harvard Business"}; | |
var customerDto = Mapper.Map<CustomerDto>(customer, | |
opts => | |
{ | |
opts.Items["FullName"] = null; | |
opts.Items["Schools"] = null; | |
}); | |
// Missing type map configuration or unsupported mapping. | |
Console.WriteLine($"Full Name: {customerDto.FullName}"); | |
Console.WriteLine($"Birth Date: {customerDto.DateOfBirth}"); | |
if (customerDto.Schools != null) | |
foreach (var schools in customerDto.Schools) | |
Console.WriteLine($"{schools.Key}: {schools.Value}"); | |
Console.ReadKey(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment