c# - 使用 AutoMapper 时出现“相同类型的实体已经具有相同的主键值”错误

标签 c# entity-framework 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();
}

关于c# - 使用 AutoMapper 时出现“相同类型的实体已经具有相同的主键值”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32403136/

相关文章:

c# - Alexa TopSites - 连续签名失败 - C# 实现

c# - 自动映射器用前缀展开

c# - Automapper AssertConfigurationIsValid 不检查 ReverseMap

c# - 校验功能。将 C 转换为 C#

c# - 如何在后台持续运行 C# 控制台应用程序

c# - 将新实体插入到具有标识主键的上下文中

.net - 在 EC2 中使用 Entity Framework 会产生 EntityException

c# - 模型类中的计算字段给出异常

Automapper 3.0 - 此平台不支持此类型 IMapperRegistry

c# - 带有小数分隔符的数字错误地转换为 Double