简体   繁体   English

自动映射:从单个源值填充的多个目标值

[英]Automapper: multiple destination values populated from single source value

My DTO (destination) has a bunch of boolean values. 我的DTO(目的地)有一堆布尔值。

For example: 例如:

HasThisOption
HasThatOption
HasSomeOtherOption

These values are populated by doing some computation on one of the fields of the model object (source). 通过在模型对象(源)的一个字段上进行一些计算来填充这些值。 This computation is a little costly, so rather than doing the same computation for every field on the DTO, I would like to only run the computation once. 这个计算有点贵,因此我不想对DTO上的每个字段进行相同的计算,我只想运行一次计算。

Simple solution is to just call a function from my controller.. ie.. PopulateFields(source, dest) 简单的解决方案是从我的控制器中调用一个函数..即.. PopulateFields(source,dest)

But I don't want to have calls to Ignore for every destination field in my mapper configuration.. because there are about 40 of them... and it just looks messy and really makes no damn sense to do so. 但是我不希望在我的映射器配置中为每个目标字段调用Ignore ..因为它们中有大约40个......而且它看起来很混乱,这样做真的没有任何意义。

What does one generally do in this situation? 在这种情况下,人们通常会做些什么?

You could use an AfterMap when defining your mapping between the source and the destination type: 在定义源和目标类型之间的映射时,可以使用AfterMap

Mapper.CreateMap<Source, Dest>().AfterMap((source, dest) =>
{
    // do your custom computations and assignments here
});

If the boolean fields are not present in the source type they will be ignored anyway during the standard mapping and have their default values in the destination. 如果源类型中不存在布尔字段,则在标准映射期间它们将被忽略,并且在目标中具有其默认值。 The AfterMap method allows you to change them. AfterMap方法允许您更改它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM