开发者

A duplicate value cannot be inserted into a unique index [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜