更新对象上下文时发生错误

Nad*_*edr 6 .net c# entity-framework exception-handling

首先,这里是消息

已成功提交对数据库的更改,但更新对象上下文时发生错误.ObjectContext可能处于不一致状态.内部异常消息:发生了引用完整性约束违规:定义引用约束的属性值在关系中的主体和从属对象之间不一致.

当我尝试在entityframework中插入新数据时,会出现问题


我的实体模型

在此输入图像描述

在数据库中,我在删除和更新时将关系设置为级联.这是我对这种关系所做的唯一改变


我的行动方法:

[HttpPost]
    public ActionResult CompleteRegisteration(RegisterViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var user = new User
                       {
                           DisplayName = model.DisplayName,
                           FullName = model.Name,
                           Email = model.Email,
                       };
        user.AuthenticationTokens.Add(new AuthenticationToken
                                          {
                                              ClaimedIdentifier = model.ClaimedIdentifier,
                                              DisplayName = model.Email
                                          });
        _userRepository.InsertOrUpdate(user);
        _userRepository.Save();

        return RedirectToAction("Index", "Home");
    }
Run Code Online (Sandbox Code Playgroud)

和用户存储库方法:

    private readonly StoryWritingEntities context = new StoryWritingEntities();

    public void InsertOrUpdate(User user)
    {
        context.Users.Attach(user);
        context.ObjectStateManager.ChangeObjectState(user,
                                                     user.Id == default(int)
                                                         ? EntityState.Added // if true then this is a new entry
                                                         : EntityState.Modified); // if false this is an Existing entry

    }
    public void Save()
    {
        context.SaveChanges();
    }
Run Code Online (Sandbox Code Playgroud)

问题是由于context.SaveChanges()在users表中插入了一条记录,但在AuthenticationTokens表中没有插入任何内容

Ian*_*cer 6

如果您只是执行以下操作,则不会发生这种情况:

  context.Users.AddObject(user);
  content.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

我怀疑问题正在发生,因为EF不知道AuthenticationToken对象,它没有附加到上下文,因为它被添加到断开连接的实体,然后附加到上下文.

您需要让EF处理整个对象图连接情况,或者您需要自己完成所有操作.像这样的混合和匹配不起作用.