title: MVC4 Unit test: Cannot insert duplicate key in object
body: <p>I'm writing a unit test for an application and I get this error but only when running my test.</p>
  
  <pre><code>Test method Tests.Items.CreateItem.CreateNewItem threw exception: 
  System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---&gt; System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---&gt; System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.Items'. Cannot insert duplicate key in object 'dbo.Items'. The duplicate key value is (e13b11ae-762f-4b86-84b3-d8224fcd84c9).
  The statement has been terminated.
  Result StackTrace:  
  at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
     at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 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&amp; dataReady)
     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&amp; task, Boolean asyncWrite, SqlDataReader ds)
     at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean asyncWrite)
     at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
     at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
     at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.&lt;NonQuery&gt;b__0(DbCommand t, DbCommandInterceptionContext`1 c)
     at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
     at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
     at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
     at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
     at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   --- End of inner exception stack trace ---
      at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
     at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.&lt;Update&gt;b__2(UpdateTranslator ut)
     at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
     at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
     at System.Data.Entity.Core.Objects.ObjectContext.&lt;SaveChangesToStore&gt;b__35()
     at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
     at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
     at System.Data.Entity.Core.Objects.ObjectContext.&lt;&gt;c__DisplayClass2a.&lt;SaveChangesInternal&gt;b__27()
     at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
     at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
     at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
     at System.Data.Entity.Internal.InternalContext.SaveChanges()
   --- End of inner exception stack trace ---
      at System.Data.Entity.Internal.InternalContext.SaveChanges()
     at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
     at System.Data.Entity.DbContext.SaveChanges()
  </code></pre>
  
  <p>This is my unit test:</p>
  
  <pre><code>[TestClass]
  public class CreateItem
  {
      Guid guiItemID = Guid.Parse("e13b11ae-762f-4b86-84b3-d8224fcd84c9");
  
      [TestMethod]
      public void CreateNewItem()
      {
          // Create element
          Item item = new Item();
          item.ID = guiItemID;
  
          // Save element to database
          TestContext db = new TestContext();
          db.Items.Add(item);
          db.SaveChanges();
      }
  </code></pre>
  
  <p>This is the ID property on my model:</p>
  
  <pre><code>[Key]
  public Guid ID { get; set; }
  </code></pre>
  
  <p>If I run the same code from my seed method the database is seeded with this item. So I know the code for interacting with the database works correctly.</p>
  
  <p>If I change:</p>
  
  <pre><code>item.ID = guiItemID;
  </code></pre>
  
  <p>to:</p>
  
  <pre><code>item.ID = Guid.NewGuid();
  </code></pre>
  
  <p>Then the test passes. But I want to set the ID so I can test other things by retrieving the same item later.</p>
  
  <p>My item does not exist already in the database. This is an empty database.</p>
  
  <p>Why does my test throw an error as if the Item already exists when it clearly doesn't? Is the test running twice somehow? It's the only test in my list.</p>