AutoMapper – 为什么要覆盖整个对象?

我不明白为什么它会覆盖我的整个对象。 原因是我从db获取了我的User对象,我想从DTO分配新值。 它不是仅仅添加这些新值,而是创建具有新值但前面所有值都设置为null新对象。

我怎样才能确保在这种情况下他会“升级”我的对象,而不是创建新对象?

脚本

/users/{id} – PUT

 // User has id, username, fullname // UserPut has fullname public HttpResponseMessage Put(int id, UserPut userPut) { var user = _db.Users.SingleOrDefault(x => x.Id == id); // filled with properties Mapper.CreateMap(); user = Mapper.Map(userPut); // now it has only "fullname", everything else set to null // I can't save it to db because everything is set to null except "fullname" return Request.CreateResponse(HttpStatusCode.OK, user); } 

Mapper.Map有一个重载,它接受一个源和一个目标对象。 在这种情况下,Automapper将使用给定的目标对象,而不会创建新对象。

所以你需要将Mapper.Map重写为:

 Mapper.Map(userPut, user);