title: error occurred while updating the object context
body: <p>first of all here is the message</p>
  
  <blockquote>
    <p>The changes to the database were
    committed successfully, but an error
    occurred while updating the object
    context. The ObjectContext might be in
    an inconsistent state. Inner exception
    message: A referential integrity
    constraint violation occurred: The
    property values that define the
    referential constraints are not
    consistent between principal and
    dependent objects in the relationship.</p>
  </blockquote>
  
  <p>the problem happens when i try to insert new data in the entityframework </p>
  
  <hr>
  
  <p>My entity model </p>
  
  <p><img src="https://i.stack.imgur.com/wdwFS.png" alt="enter image description here"></p>
  
  <p>in the database i set the relation to cascade on delete and update. that is the only change i made to the relation </p>
  
  <hr>
  
  <p>My Action Method :</p>
  
  <pre><code>[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");
      }
  </code></pre>
  
  <hr>
  
  <p>and the user repository methods : </p>
  
  <pre><code>    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();
      }
  </code></pre>
  
  <hr>
  
  <p>the problem is caused by <code>context.SaveChanges()</code> there is a record inserted in the users table but nothing is inserted in the AuthenticationTokens table </p>