Reputation: 17
Like when I add the First name, Last Name, Username and Password. For some reason I cant get it to let me add entries such as the UserId to say 1, 2, 3 and so on with the rest of the information
Instead I am getting this error when I try to register another person or make another entry to GridView1:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.Linq.dll but was not handled in user code. Additional information: Violation of PRIMARY KEY constraint 'PK__User__1788CC4C1B5B052D'. Cannot insert duplicate key
I might not have explained this well. Forgive me.
Upvotes: 1
Views: 255
Reputation: 994
1) Make the column identity: Go to column property and set Identity specification and Is Identity: make it yes and increment by value 1
OR by:
UserID INT IDENTITY(1,1) PRIMARY KEY
2) Check your ID property inside the Item class to ensure that it have attributes like this:
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert,
DbType="INT NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
Look at the IsDbGenerated=true, it is the important guy here.
Maybe you created the DatabaseContext using the designer before adjusting the IDENTITY on the Sql Server, so just regenerate this class (by deleting the table in the designer and dropping it from the Server Explorer again).
OR
In your LINQ to SQL designer, you need to make sure your column is set to:
Auto Generated Value = TRUE
Auto-Sync = ON INSERT
Hope this will help:)
Upvotes: 1
Reputation: 27009
You are getting that error is because your User
table's primary key column is not set to be an identity column. You are not setting the value of this column from your C# code, but the default is zero. Most likely you inserted one record successfully so a record with zero as the primary key got inserted. Now you are trying to insert more rows and another zero is going in so it is throwing that exception.
Fix
Make sure your User
table's primary key is set to an indentity column so it auto increments. If you do not want it to be identity and increment automatically, then you need to pass the value in but you have to make sure it is unique or you will get the same error. I would just make it identity.
Upvotes: 0
Reputation: 1569
So looks like your Key isn't auto populated. This will cause a big issue because a primary key can't be null.
In your create table TSQL in picture "User table" change the line to:
[UserID] INT NOT NULL
to
UserID INT IDENTITY(1,1) PRIMARY KEY
That should fix your problem
Caz
Upvotes: 0