简体   繁体   English

如何在C#中使用ADO.NET递增自动递增字段

[英]How to increment an auto-increment field with ADO.NET in C#

I have a database table with three fields: 我有一个包含三个字段的数据库表:

Product(ProdId, Name, Price) 产品(产品名称,名称,价格)

Where ProdId is a auto-increment field. 其中ProdId自动递增字段。 The auto-increment is with seed 1, starting from 0. 自动递增是从1开始的种子1。

I perform operation on the database by using C# in an ASP.NET application. 我通过在ASP.NET应用程序中使用C#对数据库执行操作。

If I use LINQ to INSERT a new record I just assign values to Name and Price fields and when I submit the changes the database is responsible to increment the ProdId. 如果我使用LINQ插入新记录,则只需为“名称”和“价格”字段分配值,当我提交更改时,数据库负责增加ProdId。

How can I do it with the standard ADO.NET? 如何使用标准ADO.NET? If I write an INSERT statement 如果我写一个INSERT语句

INSERT INTO Product (Name, Price) VALUES (@Name, @Price)

when I execute the command an exception is thrown; 当我执行命令时,会引发异常;

Cannot insert NULL in ProdId. 无法在ProdId中插入NULL。

Anybody has a solution? 有人有解决办法吗? Thanks 谢谢

I would start debugging in this order: 我将按以下顺序开始调试:

  • Make sure in your SQL you do have AUTO Increment on 确保在您的SQL中您确实有AUTO Increment on

在此处输入图片说明

Data Types can be numeric , money , decimal , float , bigint and int 数据类型可以是numericmoneydecimalfloatbigintint

  • using the Studio Management tool, run the insert query manually 使用Studio管理工具,手动运行插入查询

like: 喜欢:

DECLARE @Name nvarchar(100), @Price money

SET @Name = 'Bruno Alexandre';
SET @Price = 100.10;

INSERT INTO Product (Name, Price) VALUES (@Name, @Price)

or 要么

INSERT INTO Product SELECT @Name, @Price
  • Make SURE that you are pointing in your ADO Connection to the correct Database. 确保您在ADO连接中指向正确的数据库。

  • If using EF, refresh your table using the Update Table Wizard on the .edmx file 如果使用EF, 使用.edmx文件上的“更新表向导” 刷新表

您如何定义ProdId,请尝试INT NOT NULL AUTO_INCREMENT ...

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

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