c# - AutoMapper 将目标对象上的属性设置为 null

标签 c# automapper

我有这样的东西:

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);

但是当使用它时,属性 OtherEntitiesAnotherEntities设置为 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());

关于c# - AutoMapper 将目标对象上的属性设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16125997/

相关文章:

asp.net-mvc - AutoMapper 奇怪的 IQueryable 投影异常

Automapper,将多个属性映射到 1 个没有 ValueResolver

c# - 避免对单独的成员 Automapper 重复 coSTLy 方法调用

c# - 在没有 LINQ 的情况下对充满匿名类型的 List<object> 进行排序

c# - ??空合并运算符 --> 合并是什么意思?

c# - 如何让控件在窗口最大化时自行调整大小?

c# - Automapper - 缺少类型映射配置或不受支持的映射

c# - Python或C#中的项目构想

c# - 用白色替换黑色区域

c# - 将数组自动映射到列表