Automapper:对象列表中的地图属性

婴儿耶稣

我有一个 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. 在你的 then 中做 aftermapAccountService是非常有意义的。

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

   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该类的另外两分钱
您可以检查映射配置文件的创建是否正确。这将为您省去稍后在运行时遇到此问题的麻烦。您会立即知道配置有问题。

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

这也通知我,.Ignore()该上ExternalId的成员Account类是必需的:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章