Trackable entities Primary key violation EF 4 Issue

230 views Asked by At

My situation is very wierd. We have a .NET 4.5 Application that uses Tracking Entities using EF 4. Everything works fine in our DEV/QA/UAT environment. But EF fail in Production with a Primary key violation. We have a Table and a that has a foreign key with the Parent Table and that foreign key is also the primary key in the Child table.

The code that does the update gets the entity that also has the entity referenced in it. We start tracking on the and the in the Business Layer and then do a few updates and then pass to the Data Access layer to do the actual update. The code in the Data access layer is below:

    internal static TEntity EntitySave<TEntity>(this TEntity entity, bool      
    enableTracking = true) where TEntity : class, IObjectWithChangeTracker
    {
        if (entity == null)
            return entity;

        MasterEntities context = null;

        try
        {
            context = new MasterEntities();
            if (!entity.ChangeTracker.ChangeTrackingEnabled)    // This code isn't really doing anything since turning on tracking at this point doesn't matter
            {                                                   // ""
                entity.StartTracking();                         // ""
            }                                                   // ""
            context.EntityRoot<TEntity>().ApplyChanges(entity);
            context.SaveChanges();
            if (enableTracking)
                context.ResetAllTracking();
        }
        catch (Exception ex)
        {
            new GroupM.ToolLib.AppException.Ex(false, ex, "Error in RepositoryHelpers; Method: EntitySave",
                            GroupM.ToolLib.AppException.ExType.Error,
                            GroupM.ToolLib.AppException.ExDestination.AppDefaultLogFile);
        }
        finally
        {
            if (context != null)
                context.Dispose();
        }

        return entity;
    }

The stack trace is:

Exception=An error occurred while updating the entries. See the inner exception for details. Method=Update Source=System.Data.Entity StackTrace= at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at DataMarketplace.DataAccess.Repositories.RepositoryHelpers.EntitySave[TEntity](TEntity entity, Boolean enableTracking) InnerException=System.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_DataFeedQueries'. Cannot insert duplicate key in object 'dbo.DataFeedQueryState'. The duplicate key value is (3383). The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List1 generatedValues) at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) ClientConnectionId:9abb68fe-3424-45d8-a174-88ed692ac5fd Custom Message Text=Error in RepositoryHelpers; Method: EntitySave Machine Name=WEB02-PROD

I have done the following to troubleshoot:

  1. Debug the issue from my local machine and point to production database, it works fine. So it led me to believe maybe the code is not the same.
    1. I copied code from our UAT environment where this is working to Production web server. But I still get the same error. This led me to believe maybe the database schema or some other setting is not the same.
    2. Compared database schema between UAT and Prod. They are identical.

Any ideas on how to further troubleshoot this. Been trying for a couple of days now.

Thanks in advance for any suggestions.

1

There are 1 answers

4
João Silva On

I would guess that you're managing the primary keys manually instead of the database.

If that is the case, you might get two concurrent inserts for the same table with the same id, violating the Primary Key constraint.