A duplicate value cannot be inserted into a unique index [closed]
Self answering question for future reference:
If you have a table where you deleted and re-added content, you can get this error while inserting new rows with an ID equal to existing IDs:
Server Error in '/' Application.
A duplicate value cannot be inserted开发者_如何学C into a unique index. [ Table name = Stories,Constraint name = PK__Stories__000000000000001C ]
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlServerCe.SqlCeException: A duplicate value cannot be inserted into a unique index. [ Table name = Stories,Constraint name = PK__Stories__000000000000001C ]
Source Error:
Line 57:
Line 58: Public Sub Save() Implements IStoryRepository.Save
Line 59: context.SaveChanges()
Line 60: End Sub
SQL Server CE is trying to insert rows with an id (storyid in this case) equal to rows that exists.
The solution lies here:
http://msdn.microsoft.com/en-us/library/aa237859(v=sql.80).aspx
It looks like this:
ALTER TABLE Stories ALTER COLUMN storyid IDENTITY (200, 1)
What this mean is that you modify your table (Stories)'s identity column (storyid in this case) and set it to start to a bigger number than where the rows are currently at. For example, if my row with the biggest storyid is 170, I could seed it like this:
ALTER TABLE Stories ALTER COLUMN storyid IDENTITY (171, 1)
The next insert will have a storyid of 171 and then it will auto-increments.
Carl
精彩评论