While changing the object context, an error occurred.

.net c# entity-framework exception-handling


first, let me state the message.

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.

The issue arises whenever I attempt to add new data to the entityframework.

Model of my entity

enter image description here

I configured the relation in the database to cascade on update and remove. I merely changed that aspect of the relationship.

My Approach:

    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

        return RedirectToAction("Index", "Home");

and the procedures for user repository:

    private readonly StoryWritingEntities context = new StoryWritingEntities();

    public void InsertOrUpdate(User 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()

The issue is brought on bycontext.SaveChanges() the users table has a record added, but the AuthenticationTokens table has nothing.

6/7/2012 6:03:41 PM

Accepted Answer

Simply doing the following actions would prevent this:


I believe the issue exists because EF is unaware of theAuthenticationToken Due to the fact that the object is added to a detached entity before being attached to the context, it is not being associated to the context.

Either let EF handle all object graph connection issues, or take care of them all on your own. This kind of combining and matching does not function.

4/13/2011 9:35:54 PM

Popular Answer

This issue occurred when the code added a row with the same ID while I was attempting to change a record or row in the table.

I've now modified the

ctx.table.Add(entity object);


ctx.Entry(entity object).State = EntityState.Modified;

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow