我有这样的内容:
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