C# – How to insert a new record which has a auto increment number as primary key

cexception handlinglinq-to-sqlnet

For example, I have the following Table:

CustomerInfo

cus_id: auto increment, int, is Identity
cus_name: nvarchar

If I use the follow codes to insert the record "Peter",

string name = "Peter";
DataContext DC = new DataContext();
CustomerInfo newCustomer = new CustomerInfo();
newCustomer.cus_name = name;

DC.CustomerInfos.InsertOnSubmit(newCustomer);
DC.SubmitChanges();

The following error returns,

Can't perform Create, Update, or Delete operations on 'Table(CustomerInfo)' because it has no primary key.

Do I need to self-define the cus_id or any other solutions? Thanks!

Best Answer

First of all LINQ-To-SQL needs primary keys in order to be able to do Inserts and Updates, so you probably have to add the Primary Key in your table.

Now, because it is an auto incremented identity column, in your dbml, you have to select the column "cus_id" of the "CustomerInfo" table and go to the properties and set the following:

  • Auto Generated Value : True
  • Auto-Sync : OnInsert

This will ensure that when you insert a new row it will get a new id.

Related Topic