AutoMapper-为什么要覆盖整个对象? [英] AutoMapper - Why it is overwriting whole object?
问题描述
我不明白为什么它会覆盖我的整个对象.原因是我从db获得了User
对象,我想从DTO分配新值.不仅仅是添加这些新值,而是创建具有新值但所有先前值都设置为null
的新对象.
I don't understand why it's overwriting my whole object. The reason is that I get my User
object from db an I want to assign new values from DTO. Instead of just adding those new values it's creating new object that has new values but all previous are set to null
.
在这种情况下,我如何确保他将升级"我的对象,而不是创建新对象?
How can I make sure that in this case he will "upgrade" my object, not create new one?
/users/{id}
-放置
// 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<UserPut, User>();
user = Mapper.Map<User>(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将使用给定的目标对象,并且不会创建新对象.
The Mapper.Map
has an overload which takes a source and a destination object. In this case Automapper will use the given destination object and does not create a new object.
因此您需要将Mapper.Map
重写为:
Mapper.Map<UserPut, User>(userPut, user);
这篇关于AutoMapper-为什么要覆盖整个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!