Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper - Why it is overwriting whole object? [duplicate]

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);
}
like image 814
Stan Avatar asked Aug 10 '13 15:08

Stan


1 Answers

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);
like image 123
nemesv Avatar answered Oct 21 '22 03:10

nemesv