'entity of the same type already has the same primary key value' 使用 AutoMapper 时出错

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

当我使用 AutoMapper 时,出现了这个错误:

Attaching an entity of type 'MyProject.DAL.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

我想在从数据库中检索时将 User 映射到 UserModel。我更改 UI 中的 UserModel 属性,然后再次将其映射到 User 并更新它。 我的代码在这里:

public UserModel GetUserByUserId(int id)
    {
        var user = db.Users.Where(p => p.UserId == id).FirstOrDefault();
        var userModel = Mapper.Map<UserModel>(user);
        return userModel;
    }

public void Update(UserModel userModel)
    {
        var user = Mapper.Map<User>(userModel);
        db.Entry(user).State = EntityState.Modified;
        db.SaveChanges();
    }

但是如果我不使用自动映射器并编写类似下面的代码,它可以正常工作。

public void Update(UserModel userModel)
    {
        updatingUser.Email = userModel.Email;
        updatingUser.FirstName = userModel.FirstName;
        updatingUser.ModifiedDate = DateTime.Now;
        updatingUser.LastName = userModel.LastName;
        updatingUser.Password = userModel.Password;
        updatingUser.UserName = userModel.UserName;

        db.Entry(updatingUser).State = EntityState.Modified;
        db.SaveChanges();
    }

我该怎么办:

这可能只是我不了解某些功能,但您的 update 功能对我来说看起来很时髦。我看不出它如何将您的新 user 与数据库中现有的相关联。

这就是我的处理方式。

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

或者,如果您更喜欢像第二个 update 函数那样做

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

对象 A 和他的子对象 B,然后设置所有属性,然后将其刷新到 . 我们不再:附上(之前的对象 A 和 B) 我们不再单独获取对象 B。