Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while inserting data with LINQ to SQL

Tags:

c#

linq

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.

like image 774
mohammad reza Avatar asked Dec 29 '22 18:12

mohammad reza


1 Answers

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

like image 128
bruno conde Avatar answered Jan 01 '23 17:01

bruno conde