[英]How to use Mapper.Map with ConstructUsing and AutoMapper?
I have a simple question: How to use Mapper.Map
inside ConstructUsing
?我有一个简单的问题:如何在
ConstructUsing
中使用Mapper.Map
? I'm using AutoMapper v4.1.1 and I have this piece of code that I want to cleanup by reusing the code.我正在使用 AutoMapper v4.1.1,我有这段代码,我想通过重用代码来清理。
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));
我知道我们可以像这样将
Mapper.Map
与AfterMap
方法一起使用.AfterMap((s, d) => Mapper.Map(s.CompanyProfile, d));
But I'm not able to do the same inside ConstructUsing
.但是我无法在
ConstructUsing
中做同样的事情。
Any suggestion?有什么建议吗?
David大卫
Since you have mappings defined for these entities, you could call Mapper.Map on it.由于您已经为这些实体定义了映射,因此您可以在其上调用 Mapper.Map。 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:然后,当您需要创建一个由 automapper 映射的对象时,只需使用:
var viewModel = Mapper.Map<List<SKUViewModel>>(sku);
Methods like ConstructUsing
, AfterMap
, BeforeMap
are methods that is executed after you have everything defined. ConstructUsing
、 AfterMap
、 BeforeMap
等方法是在定义完所有内容后执行的方法。 So, following this logic, it should execute Mapper.Map<>
without problems.因此,按照这个逻辑,它应该可以毫无问题地执行
Mapper.Map<>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.