我有这样的事情:
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
到{{1}的映射之前它们具有值}。我怎样才能避免这种情况,以便他们真的合并而不仅仅是替换值?
感谢您的帮助。
答案 0 :(得分: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());