title: How to fix "Violation of UNIQUE KEY constraint"
body: <p>I am using Entity Framework to Add a User to the database. <strong>When I add the first user to the database, it works. When I try to add another user to the database, I get the error</strong>: System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint  </p>
  
  <p>I'm not too sure what I am doing here. I've even made an IF Condition to check weather the key is unique but the actual error messages saying i'm inserting a duplicate key. </p>
  
  <p>So here is my current code:</p>
  
  <pre><code>//Create new GUID
  string newGuid = Guid.NewGuid().ToString();
  
  //Checking if Primary Key already exists in table
  if (!context.Users_tbl.Any(u =&gt; u.UserID == newGuid))
  {
  
  //Installise New User Class
  var user = new Users_tbl()
  {
  UserID = newGuid,
  Email = email,
  Password = AESCrypt.Encrypt(password),
  };
  
  //Add User to ADO and Commit Changes
  context.Users_tbl.Add(user);
  context.SaveChanges();
  
  //Find UserID via Email
  var userID = context.Users_tbl.Where(p =&gt; p.Email == email).Select(p =&gt; p.UserID).FirstOrDefault();
  
  //Installise New UserInfo Class
  var usersInfo = new UsersInfo_tbl()
  {
  FKUserID = userID,
  FirstName = firstName,
  LastName = lastName
  };
  
  //Add User to ADO and Commit Changes
  context.UsersInfo_tbl.Add(usersInfo);
  context.SaveChanges();
  
  //Send Activation Link via Email
  SendActivationEmail(userID);
  
  //Set Session ID
  Session["UserID"] = userID;
  Response.Redirect("/Dashboard/DashBoard.aspx", false);
  }
  
  </code></pre>
  
  <p>Below is the exact error message I am getting.</p>
  
  <pre><code>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 UNIQUE KEY constraint 'UQ__Users_tb__2B5B96C51C3AA70E'. Cannot insert duplicate key in object 'dbo.Users_tbl'. The duplicate key value is (&lt;NULL&gt;).
  The statement has been terminated.
     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, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
     at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task&amp; task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
     at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean&amp; usedCache, Boolean asyncWrite, Boolean inRetry)
     at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean&amp; usedCache, Boolean asyncWrite, Boolean inRetry)
     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()
     at ReapStreamV2.Auth.Signup.SignUp.Submit_Click(Object sender, EventArgs e) in C:\Users\Milan\Documents\ReapStream DEV\ReapStream\ReapStreamV2\Auth\Signup\SignUp.aspx.cs:line 123
  </code></pre>
  
  <p>My Primary Key is Unique;</p>
  
  <pre><code>```
  CREATE TABLE [dbo].[Users_tbl] (
      [UserID]            NVARCHAR (128) NOT NULL,
      [Email]             VARCHAR (255)  NOT NULL,
      [Password]          VARCHAR (255)  NOT NULL,
      [IsTwoFAEnabled]    BIT            NOT NULL,
      [TwoFACode]         NVARCHAR (128) NULL,
      [hasActivated]      BIT            NOT NULL,
      [AccessFailedCount] INT            NOT NULL,
      CONSTRAINT [PK__Users_tb__1788CCAC29DEB237] PRIMARY KEY CLUSTERED ([UserID] ASC),
      CONSTRAINT [UQ__Users_tb__2B5B96C51C3AA70E] UNIQUE NONCLUSTERED ([TwoFACode] ASC)
  );
  
  ```
  </code></pre>