Created
February 14, 2018 08:22
-
-
Save anonymous/511a1b69b795aa2bc7e7cd261fcb98b1 to your computer and use it in GitHub Desktop.
Automapper ForAllMaps is ignored
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; | |
using System.Collections.Generic; | |
namespace AutoMapperGlitch | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var semester = new Semester | |
{ | |
Id = 42, | |
RowId = Guid.NewGuid(), | |
Name = "SemesterName" | |
}; | |
var dto = semester.ToDTO(); | |
Console.WriteLine($"{dto.Name} ({dto.Id})"); | |
Console.ReadLine(); | |
} | |
} | |
static class CurriculumMapper | |
{ | |
private static IMapper Mapper { get; } | |
static CurriculumMapper() | |
{ | |
Mapper = new MapperConfiguration(cfg => | |
{ | |
cfg.CreateMap<Semester, SemesterDTO>(); | |
cfg.ForAllMaps(MapId); | |
}).CreateMapper(); | |
} | |
private static void MapId(TypeMap map, IMappingExpression mex) | |
{ | |
if (!map.SourceType.IsSubclassOf(typeof(EntityBase))) | |
return; | |
if (!map.DestinationType.IsSubclassOf(typeof(DTOBase))) | |
return; | |
mex.ForMember("Id", opt => opt.MapFrom("RowId")); | |
} | |
public static SemesterDTO ToDTO(this Semester entity) => Mapper.Map<SemesterDTO>(entity); | |
} | |
#region Types | |
class EntityBase | |
{ | |
public int Id { get; set; } | |
public Guid RowId { get; set; } | |
} | |
class Semester : EntityBase | |
{ | |
public string Name { get; set; } | |
} | |
class DTOBase | |
{ | |
public Guid Id { get; set; } | |
} | |
class SemesterDTO :DTOBase | |
{ | |
public string Name { get; set; } | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment