AutoMapper - Why it is overwriting whole object? [

2019-05-11 04:48发布

问题:

This question already has an answer here:

  • Automapper: Update property values without creating a new object 3 answers

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?

Scenario

/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);
}

回答1:

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.

So you need to rewrite your Mapper.Map to:

Mapper.Map<UserPut, User>(userPut, user);