4

When I insert data with the following code, I see the exception. What should I do?

Code:

Movie_List_DBDataContext Movie_list1 = new Movie_List_DBDataContext();
Actor act = new Actor();

act.Actor_Name = Acttxt.Text;

Movie_list1.Actors.InsertOnSubmit(act);
Movie_list1.SubmitChanges();

Exception:

Violation of PRIMARY KEY constraint 'PK_Actors'. Cannot insert duplicate key in object 'dbo.Actors'.

My table has 2 columns; ID and Name, and ID is Primary Key.

3 Answers 3

6

In your .dbml designer make sure that the ID field is marked as "Auto Generated Value". You can found this in the properties view of the field.

Normally, this is initialized accordingly to the table in the database so, if the ID is set as an auto generated value in the database, the designer will automatically set the "Auto Generated Value" to true.

You can also mark the desired field as an "Auto Generated Value" in the code.

Search the ID property in the generated code behind and set the value in the Column attribute : IsDbGenerated=true

Sign up to request clarification or add additional context in comments.

2 Comments

Where Do I search ID property?
The ID property should be in the designer inside the table Actor.
3

Have you set "ID" in the Actor-table as an identity-field? If you haven't, a quick search on google or stack overflow will show you how. Also make sure that the autogenerate property is set in your designer-file for the ID column.

Comments

1

It looks like you expect the ID to be autogenerated. If that is the case, make sure that the property in the designer is set appropriately. The easiest way to do this, once the column is correctly configured, is to delete the table from the designer and then add it back. It should pick up the identity property on the field and configure it so that it doesn't try to insert it when the record is added. Of course, if you don't have it set as an identity property in the table, you either need to do that first or figure out a way to generate the id and assign it a unique value prior to doing the insert.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.