Automapper:在对象列表中映射 属性

Automapper: Map property in list of objects

我有一个 DTO 列表,想将此列表映射到一个实体列表。实体本身有一个 属性 来自另一个来源。我可以用一张地图将此 属性 映射到列表中的所有项目吗?

我的类:

实体:

public class Account
{
   public int Id {get;set;}
   public string Name {get;set;}
   public Guid ExternalId {get;set;}
}

DTO:

public class ExternalAccountDto
{
   public int Id {get;set;}
   public string Name {get;set;}
}

我的服务:

public class AccountService
{
   public async Task AddExternalAccounts(Guid externalId, List<ExternalAccountDto> accounts)
   {            
        var entities = _mapper.Map(accounts);
        // TODO: Map 'externalId' to all entities
        // _mapper.Map(externalId, entities); // DOES NOT WORK!

        _context.Create(entities);
   }

}

映射

public class AccountProfile: Profile
{
   public AccountProfile()
   {
      CreateMap<ExternalAccountDto, Account>();

      // TODO: CreateMap for Guid on every Account
   }
}

谁能给我一些建议!

您应该使用 AfterMap 函数对映射的项目进行一些后处理。

有两种方法可以解决这个问题。一种是使用映射配置文件中静态定义的内容。但在你的情况下,你有一些在运行时动态的东西,比如 ExternalId。在你的 AccountService 中做后期图就很有意义了。

我发现这类构造非常有用,尤其是当我想咨询其他注入服务以获取更多信息时。

   public void AddExternalAccounts(Guid externalId, List<ExternalAccountDto> accounts)
    {
        var entities = _mapper.Map<List<ExternalAccountDto>, List<Account>>(accounts, 
            options => options.AfterMap((source, destination) =>
                {
                    destination.ForEach(account => account.ExternalId = externalId);
                }));
    }

关于 AccountProfile class 的两美分:
您可以在创建映射配置文件时检查映射配置文件是否正确。这将使您以后在运行时不再为这个问题头疼运行。您会立即知道配置有问题。

 var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<MappingProfile>();
            cfg.AllowNullDestinationValues = false;
        });

        // Check that there are no issues with this configuration, which we'll encounter eventually at runtime.
        config.AssertConfigurationIsValid();

        _mapper = config.CreateMapper();

这还通知我 Account class 的 ExternalId 成员需要一个 .Ignore()

 CreateMap<ExternalAccountDto, Account>().ForMember(d => d.ExternalId, a => a.Ignore());