问题
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!
回答1:
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.
回答2:
naratting from answer 1 of question you'll have to make cus_id as primary key too. you can also try to do following
CREATE TABLE Customers
(
cus_id int NOT NULL AUTO_INCREMENT,
cus_name varchar(255) NOT NULL,
PRIMARY KEY (cus_id)
)
回答3:
I got this error to. As far as I manged to fix it was to add a primary key. This code made me a primary key and made it autoincrement. Maybe it's what you are looking for? (When you create the table)
columnname bigint IDENTITY(1,1) NOT NULL,
CONSTRAINT pkcolumnname PRIMARY KEY CLUSTERED
来源:https://stackoverflow.com/questions/17962815/how-to-insert-a-new-record-which-has-a-auto-increment-number-as-primary-key