I have a simple question: How to use Mapper.Map
inside ConstructUsing
? I'm using AutoMapper v4.1.1 and I have this piece of code that I want to cleanup by reusing the code.
Mapper.CreateMap<SKU, SKUViewModel>()
.ConstructUsing(m => new SKUViewModel(
(from texts in m.DescriptionTranslation.TranslationTexts
select new TranslationTuple
{
LanguageId = texts.LanguageId,
LanguageDisplayName = texts.Language.DisplayName,
TranslationText = texts.Text,
NeutralText = texts.NeutralText,
ThreeLetterIsoLanguageName = texts.Language.ThreeLetterISOLanguageName
}).ToList(),
(from texts in m.DisplayNameTranslation.TranslationTexts
select new TranslationTuple
{
LanguageId = texts.LanguageId,
LanguageDisplayName = texts.Language.DisplayName,
TranslationText = texts.Text,
NeutralText = texts.NeutralText,
ThreeLetterIsoLanguageName = texts.Language.ThreeLetterISOLanguageName
}).ToList(),
(from texts in m.PaypalDescriptionTranslation.TranslationTexts
select new TranslationTuple
{
LanguageId = texts.LanguageId,
LanguageDisplayName = texts.Language.DisplayName,
TranslationText = texts.Text,
NeutralText = texts.NeutralText,
ThreeLetterIsoLanguageName = texts.Language.ThreeLetterISOLanguageName
}).ToList()));
I know we can use Mapper.Map
with the AfterMap
method like this .AfterMap((s, d) => Mapper.Map(s.CompanyProfile, d));
But I'm not able to do the same inside ConstructUsing
.
Any suggestion ?
David
If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.
AutoMapper is one of the popular object-object mapping libraries with over 296 million NuGet package downloads. It was first published in 2011 and its usage is growing ever since. Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.
Since you have mappings defined for these entities, you could call Mapper.Map on it. For sample:
Mapper.CreateMap<SKU, SKUViewModel>()
.ConstructUsing(m =>
{
var descriptions = Mapper.Map<List<TranslationTuple>>(m.DescriptionTranslation.TranslationTexts);
var displays = Mapper.Map<List<TranslationTuple>>(m.DisplayNameTranslation.TranslationTexts);
var paypals = Mapper.Map<List<TranslationTuple>>(m.PaypalDescriptionTranslation.TranslationTexts);
return new SKUViewModel(descriptions, displays, paypals);
});
Then, when you need to create an object mapped by automapper, just use:
var viewModel = Mapper.Map<List<SKUViewModel>>(sku);
Methods like ConstructUsing
, AfterMap
, BeforeMap
are methods that is executed after you have everything defined. So, following this logic, it should execute Mapper.Map<>
without problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With