【问题标题】:AutoMapper - Why it is overwriting whole object? [duplicate]AutoMapper - 为什么它覆盖整个对象? [复制]
【发布时间】:2013-08-12 09:03:27
【问题描述】:

我不明白为什么它会覆盖我的整个对象。原因是我从 db 获取了我的 User 对象,并且我想从 DTO 分配新值。它不仅仅是添加这些新值,而是创建具有新值的新对象,但之前的所有值都设置为null

我如何确保在这种情况下他会“升级”我的对象,而不是创建新对象?

场景

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

【问题讨论】:

    标签: c# automapper dto automapping automapper-2


    【解决方案1】:

    Mapper.Map 有一个重载,它接受一个源和一个目标 对象。在这种情况下,Automapper 将使用给定的目标对象,并且不会创建新对象。

    所以您需要将您的Mapper.Map 重写为:

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

    【讨论】:

    • 另请注意,您不需要指定类型,因为它需要两个参数的类型。
    猜你喜欢
    • 2015-06-18
    • 2020-04-04
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多