AutoMapper将目标对象的属性设置为空

本文关键字:设置 属性 目标对象 AutoMapper | 更新日期: 2023-09-27 18:10:14

我有这样的东西:

public class DomainEntity
{
    public string Name { get; set; }
    public string Street { get; set; }
    public IEnumerable<DomainOtherEntity> OtherEntities { get; set; }
    public IEnumerable<DomainAnotherEntity> AnotherEntities { get; set; }
}
public class ApiEntity
{
    public string Name { get; set; }
    public string Street { get; set; }
    public int OtherEntitiesCount { get; set; }
}

和以下映射器配置:

Mapper.Configuration.AllowNullCollections = true;
Mapper.CreateMap<DomainEntity, ApiEntity>().
    ForSourceMember(e => e.OtherEntities, opt => opt.Ignore()).
    ForSourceMember(e => e.AntherEntities, opt => opt.Ignore()).
    ForMember(e => e.OtherEntitiesCount, opt => opt.MapFrom(src => src.OtherEntities.Count()));
Mapper.CreateMap<ApiEntity, DomainEntity>().
    ForSourceMember(e => e.OtherEntitiesCount, opt => opt.Ignore()).
    ForMember(e => e.OtherEntities, opt => opt.Ignore()).
    ForMember(e => e.AnotherEntities, opt => opt.Ignore());

从DomainEntity中获取ApiEntity,我使用var apiEntity = Mapper.Map<DomainEntity, ApiEntity>(myDomainEntity);

从ApiEntity中获得合并的DomainEntity,我使用var domainEntity = Mapper.Map(myApiEntity, myDomainEntity);

但是当使用这个时,属性OtherEntitiesAnotherEntities被设置为null -即使它们在调用从myApiEntitymyDomainEntity的映射之前有值。我怎样才能避免这种情况,使他们真的合并,而不仅仅是替换值?

谢谢你的帮助

AutoMapper将目标对象的属性设置为空

我想你是在寻找UseDestinationValue而不是Ignore:

Mapper.CreateMap<ApiEntity, DomainEntity>().
    ForSourceMember(e => e.OtherEntitiesCount, opt => opt.UseDestinationValue()).
    ForMember(e => e.OtherEntities, opt => opt.UseDestinationValue()).
    ForMember(e => e.AnotherEntities, opt => opt.UseDestinationValue());