我有这样的事情:

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的映射之前具有值。如何避免这种情况,使它们真正合并而不仅仅是替换值?

谢谢你的帮助。

最佳答案

我认为您正在寻找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());

关于c# - AutoMapper将属性设置为目标对象上的null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16125997/

10-09 02:29