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

9

我有这样的内容:

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); 但是,在使用时,属性OtherEntities和AnotherEntities被设置为null - 即使在调用从myApiEntity到myDomainEntity的映射之前它们已经有值。我该如何避免这种情况,以便它们真正地合并而不仅仅是替换值?
感谢任何帮助。

你正在使用哪个版本的 AutoMapper? 在 2.2.1 上,你的情况对我来说工作得很好。 - Mightymuke
我正在使用NuGet上最新的版本,目前是2.2.1。 - Felix C
1个回答

12

我认为你要使用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());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接