2013-08-10 3 views
2

왜 내 전체 개체를 덮어 쓰는 지 이해할 수 없습니다. 그 이유는 db0에서 내 User 개체를 얻고 DTO에서 새 값을 할당하려고하기 때문입니다. 새 값을 추가하는 대신 새 값을 갖는 새 개체를 만들지 만 이전 값은 모두 null으로 설정됩니다.AutoMapper - 전체 개체를 덮어 쓰는 이유는 무엇입니까?

이 경우 어떻게하면 내 개체를 "업그레이드"하고 새로 만들지 않을 수 있습니까?

시나리오

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

답변

6

Mapper.Map는 소스 및 목적지 오브젝트를 가지고 과부하 넣어. 이 경우 Automapper는 지정된 대상 객체를 사용하며 새 객체를 만들지 않습니다.

그래서 당신이 다시 작성해야 당신의 Mapper.Map에 :

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

은 또한 두 개의 인수의 형태를 취 당신이 유형을 지정할 필요가 없습니다. –