here's the first message
The changes to the database were successful, but an error occurred while updating the context object. The object may be in an inconsistent state. Internal exception message: referential integrity violation of the constraint occurred: the values โโof the properties that define the referential constraints are not consistent between the principal and the dependent objects in relation.
the problem occurs when I try to insert new data in entityframework
My entity model
in the database, I set the cascade relation when deleting and updating. this is the only change I made for the relationship
My action method:
[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"); }
and user repository methods:
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(); }
The problem is because context.SaveChanges()
has a record inserted in the users table, but nothing is inserted in the AuthenticationTokens table
source share