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

Sta*_*tan 3 c# dto automapping automapper automapper-2

我不明白为什么它会覆盖我的整个对象.原因是我User从db 获取对象,我想从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<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);
}
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 8

Mapper.Map具有过载,这需要源和目的地对象.在这种情况下,Automapper将使用给定的目标对象,而不会创建新对象.

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

Mapper.Map<UserPut, User>(userPut, user);
Run Code Online (Sandbox Code Playgroud)