简体   繁体   English

如何插入一个具有自动增量编号作为主键的新记录?

[英]How to insert a new record which has a auto increment number as primary key?

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. 无法对“Table(CustomerInfo)”执行“创建”,“更新”或“删除”操作,因为它没有主键。

Do I need to self-define the cus_id or any other solutions? 我是否需要自定义cus_id或任何其他解决方案? Thanks! 谢谢!

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. 首先,LINQ-To-SQL需要主键才能进行插入和更新,因此您可能需要在表中添加主键。

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: 现在,因为它是一个自动递增的标识列,所以在dbml中,必须选择“CustomerInfo”表的“cus_id”列,然后转到属性并设置以下内容:

  • Auto Generated Value : True 自动生成值 :正确
  • Auto-Sync : OnInsert 自动同步 :OnInsert

This will ensure that when you insert a new row it will get a new id. 这将确保当您插入新行时,它将获得一个新ID。

naratting from answer 1 of question you'll have to make cus_id as primary key too. 从答案1 naratting的问题 ,你将不得不作出cus_id作为主键也。 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)
)

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM