'entity of the same type already has the same primary key value' error using AutoMapper

痴心易碎 提交于 2019-12-05 22:01:33

This might just be me being unaware of some features, but your update function looks funky to me. I don't see how it would associate your new user with the existing one in the db.

This is how I would approach it.

public void Update(UserModel userModel)
{
    var user = db.Users.Find(userModel.UserId);
    Mapper.Map(userModel, user);
    db.SaveChanges();
}

or, if you prefer to do it like your second update function does

public void Update(UserModel userModel)
{
    Mapper.Map(userModel, updatingUser);
    db.Entry(updatingUser).State = EntityState.Modified;
    db.SaveChanges();
}

object A and his child object B and then setting all properties from and then flushing it towards the . We no longer: attached the (Object A and B from previous ) We no longer fetched object B separately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!