加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用AutoMapper,“相同类型的实体已经具有相同的主键值”

发布时间:2020-12-15 23:46:52 所属栏目:百科 来源:网络整理
导读:当我使用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 sta
当我使用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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读