tags:

views:

299

answers:

3

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.

+2  A: 

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.

Espo
+1  A: 

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.

tvanfosson
+2  A: 

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

bruno conde
Where Do I search ID property?
mohammad reza
The ID property should be in the designer inside the table Actor.
bruno conde