entity-frameworkc#-4.0asp.net-mvc-4objectstatemanager

optimistic concurrency exception was handled by the user code


I'm using MVC4 with Entity Framework 4.1.

Initially we have created an Ado.net entity model from database. In the .edmx file, some of the tables that are in the database are not visible as they dont posses the primary key on particular table.

As our project is moving forward, we need to update to one of the log tables which dont have a primary key field.

So, we modified our .edmx file instead of modifying in the database. our client asked us not to modify the database fields. we have modified the .edmx and created a pk on one of the exisiting field in the table(say tbl_log table).

we are trying to update the tbl_log. But it gives an error message as Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

I've seen much of questions in stack overflow and also googled a bit, but could not find any solution.

Even i've tried refreshing the ObjectStateManager entries but it still points to the same error.

Here is my code

    tbl_log log = new tbl_log();

                    Entity.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified);

    log.LoginId = strLoginId;
    log.Password = strPassword;
    log.IPAddress = strIpAddress;
    log.Date_Time = DateTime.Parse(DateTime.Now.ToString());
    log.sessionId = new Guid(strSessionId);

    Entity.AddTotbl_log(log);

Entity.SaveChanges();// optimistic concurrency error

Please help

Thanks,

Karthik


Solution

  • Your model must represent the database schema. If you add a PK to the model it should exist in the database as well, otherwise you will get errors. It's generally bad practice to not have a PK on any table, even if the table is an audit log table.

    What the exception is telling you is that the object tracker cannot determine if the state of the object has changed since the last call to the database. This is because the PK you have set is still 0 even after the framework has sent the insert/update query.

    Unfortunately there is no good way to work around this. I would suggest (as I think Microsoft does) to add a primary key column to every table in your database.

    EDIT - From comments

    As the PK is used to track the object, if you have set the PK to have a StoreGenerationPattern of Identity in your model it will be expecting the value to change. When it doesn't change then it will throw the error your are seeing. Try changing the StoreGenerationPattern to None as then EF won't be expecting your faux-PK to change