Skip to content

Instantly share code, notes, and snippets.

Created February 14, 2018 08:22
Show Gist options
  • Save anonymous/511a1b69b795aa2bc7e7cd261fcb98b1 to your computer and use it in GitHub Desktop.
Save anonymous/511a1b69b795aa2bc7e7cd261fcb98b1 to your computer and use it in GitHub Desktop.
Automapper ForAllMaps is ignored
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