我有这样的事情:
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 获取 ApiEntityvar apiEntity = Mapper.Map<DomainEntity, ApiEntity>(myDomainEntity);
从我正在使用的 ApiEntity 获取合并的 DomainEntityvar domainEntity = Mapper.Map(myApiEntity, myDomainEntity);
但是当使用它时,属性OtherEntities
和AnotherEntities
被设置为null
- 即使它们在调用映射 from myApiEntity
to之前有值myDomainEntity
。我怎样才能避免这种情况,以便它们真正合并而不仅仅是替换值?
谢谢你的帮助。