我有以下代码:
-
将实体转换为dto
-
更新dto中的属性
-
将数据转换回实体
-
使用更新的属性更新原始实体
这几乎可以工作,但在最终更新期间-其中一个字段被设置为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; }
}