c# – 使用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时将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();
    }

我该怎么办:

解决方法:

这可能只是我不知道某些功能,但你的更新功能看起来很时髦.我不知道它将如何将您的新用户与数据库中的现有用户相关联.

这就是我接近它的方式.

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

或者,如果您喜欢像第二次更新功能那样做

public void Update(UserModel userModel)
{
    Mapper.Map(userModel, updatingUser);
    db.Entry(updatingUser).State = EntityState.Modified;
    db.SaveChanges();
}
上一篇:C#-Automapper和NHibernate:延迟加载


下一篇:c# – 如何配置Automapper 4以允许空目标值