代码之家  ›  专栏  ›  技术社区  ›  TomSelleck

自动映射用null覆盖嵌套字段

  •  0
  • TomSelleck  · 技术社区  · 6 年前

    我有以下代码:

    1. 将实体转换为dto
    2. 更新dto中的属性
    3. 将数据转换回实体
    4. 使用更新的属性更新原始实体

    这几乎可以工作,但在最终更新期间-其中一个字段被设置为null,但不应触摸它。

    主要内容:

    Entity e = new Entity("Id")
    {
        Additional = new EntityAdditional()
        {
            Editable = "Change Me!",
            NotEditable = "Don't Change Me!"
        }
    };
    
    Dto dto = Mapper.Map<Dto>(e);
    
    dto.Additional.Editable = "Changed!";
    
    Mapper.Map<Dto, Entity>(dto, e); // e NotEditable is null!
    

    映射:

    config.CreateMap<Entity, Dto>()
        .ForMember(d => d.Additional,
        input => input.MapFrom(i => new DtoAdditional{
            Editable = i.Additional.Editable
        }));
    
    config.CreateMap<Dto, Entity>()
        .ForMember(d => d.Additional,
        input => input.MapFrom(i => new EntityAdditional
        {
            Editable = i.Additional.Editable
        }));
    

    实体:

    public class Entity
    {
        public string Id { get; set; }
        public EntityAdditional Additional { get; set; }
    
        public Entity(string id) {
            Id = id;
            Additional = new EntityAdditional()
            {
                Editable = "Editable",
                NotEditable = "UnEditable"
            };
        }
    }
    
    public class EntityAdditional
    {
        public string Editable { get; set; }
        public string NotEditable { get; set; }
    }
    

    Dto:

    public class Dto
    {
        public DtoAdditional Additional { get; set; }
    }
    
    public class DtoAdditional
    {
        public string Editable { get; set; }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   aaron    6 年前

    这是因为您指定了:

    new EntityAdditional
    {
        Editable = i.Additional.Editable
    //, NotEditable = null // Default value
    }));
    

    无需自定义映射:

    Mapper.CreateMap<EntityAdditional, DtoAdditional>()
        .ReverseMap();
    
    Mapper.CreateMap<Entity, Dto>()
        .ReverseMap();