SparkyTools: AutoMapper

part of the “SparkyTools” suite of .NET utility libraries

Photo by Jason Leung on Unsplash
NuGet Package | Source Code

AutoMapper is a really great tool for easily and declaratively specifying how to map objects from one type to another. I enjoy using it with “out of the box” (Why do we still say that? When was the last time software came in a box?) syntax, but enjoy using it even more with some extension methods that enable simpler syntax…

Without SparkyTools.AutoMapper:

Mapper.Initialize(cfg => cfg.CreateMap<Foo, Bar>()
.ForMember(dest => dest.Status,
opt => opt.MapFrom(src => src.StatusCode))
.ForMember(dest => dest.Comments,
opt => opt.NullSubstitute("(none)"))
.ForMember(dest => dest.IsImportant, opt => opt.UseValue(true))
.ForMember(dest => dest.UniqueId,
opt => opt.UseValue(Guid.NewGuid()))
.ForMember(dest => dest.Useless, opt => opt.Ignore());

With SparkyTools.AutoMapper:

Mapper.Initialize(cfg => cfg.CreateMap<Foo, Bar>()
.ForMember(dest => dest.Status).MapFrom(src => src.StatusCode)
.ForMember(dest => dest.Comments).NullSubstitute("(none)")
.ForMember(dest => dest.IsImportant).UseValue(true)
.ForMember(dest => dest.UniqueId).UseValue(Guid.NewGuid())
.ForMember(dest => dest.Useless).Ignore();

Ignoring members can be simplified even further.

.ForMember(dest => dest.Useless).Ignore()

…can be coded as:

.IgnoreMember(dest => dest.Useless)

.MappedTo extension method

The package also contains an extension method that allows you to replace:

Bar bar = Mapper.Map<Foo, Bar>(foo);


Bar bar = foo.MappedTo<Bar>();