[英]Automapper If source is null, set destination object properties
[英]AutoMapper settings properties to null on destination object
我有这样的事情:
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
的映射之前有值。 我怎样才能避免这种情况,以便它们真正融合而不仅仅是取代价值?
谢谢你的帮助。
我想你正在寻找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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.