Last active
December 29, 2018 09:21
-
-
Save nikanos/981493715ccd9e184e63cf8a8cad5f3a to your computer and use it in GitHub Desktop.
AutomapperTest
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
using System; | |
namespace AutoMapperTest.CLI | |
{ | |
class PersonDTO | |
{ | |
public Guid? ID { get; set; } | |
public string Name { get; set; } | |
public int? Age { get; set; } | |
public string Description { get; set; } | |
} | |
class Person | |
{ | |
public Guid ID { get; set; } | |
public string Name { get; set; } | |
public int Age { get; set; } | |
public string Description { get; set; } | |
} | |
} |
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
using AutoMapper; | |
using System; | |
namespace AutoMapperTest.CLI | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Mapper.Initialize(config => | |
{ | |
config.CreateMap<PersonDTO, Person>().ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); | |
//specific for int? in source and int in destination | |
//config.ForAllPropertyMaps(pm => pm.SourceType == typeof(int?) && pm.DestinationType == typeof(int), (pm, mo) => mo.UseDestinationValue()); | |
//generic for matching nullable in source and non nullable in destination | |
config.ForAllPropertyMaps(pm => Nullable.GetUnderlyingType(pm.SourceType) == pm.DestinationType, (pm, mo) => mo.UseDestinationValue()); | |
}); | |
var dto = new PersonDTO { ID = null, Name = "namedto", Age = 140, Description = "descriptiondto" }; | |
var entity = new Person { ID = Guid.Parse("1658f9e3-e361-4ac5-a9a1-d57e43b3e135"), Name = "name", Age = 40, Description = "description" }; | |
Mapper.Map(dto, entity); | |
Console.WriteLine("ID:" + entity.ID);//1658f9e3-e361-4ac5-a9a1-d57e43b3e135 | |
Console.WriteLine("Name:" + entity.Name);//namedto | |
Console.WriteLine("Description:" + entity.Description);//descriptiondto | |
Console.WriteLine("Age:" + entity.Age);//140 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment