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

Fel*_*x C 7 c# automapper

我有这样的事情:

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; }
}
Run Code Online (Sandbox Code Playgroud)

并遵循映射器配置:

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());
Run Code Online (Sandbox Code Playgroud)

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

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

但是使用这个时候,属性OtherEntitiesAnotherEntities设置为null-即使他们呼吁从映射之前有值myApiEntitymyDomainEntity.我怎样才能避免这种情况,以便它们真正合并而不仅仅是替换价值?

谢谢你的帮助.

And*_*ker 9

我想你正在寻找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());
Run Code Online (Sandbox Code Playgroud)