SparkyTools: AutoMapper

Brian Schroer
Mar 5, 2018 · 1 min read

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);

…with:

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

Brian Schroer

Written by

I heart writing code.

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade