Warm tip: This article is reproduced from serverfault.com, please click

sql server-使用C#错误“无法在表中为标识列插入显式值”

(sql server - Error "Cannot insert explicit value for identity column in table" using C#)

发布于 2020-11-28 07:47:09

我在使用简单的本地SQL数据库时遇到问题。我不太了解数据库或使用C#访问它们,因此将不胜感激。我正在尝试使用C#通过Linq to SQL将条目添加到数据库中的表之一。这是我的代码片段。

using (DataClasses1DataContext db = new DataClasses1DataContext())
{
    tbl_Inventory inv = new tbl_Inventory();
    inv.Title = addTitleTextBox.Text;
    inv.Model = addModelTextBox.Text;
    inv.Category = addCategoryTextBox.Text;
    inv.Quantity = int.Parse(addQuantityTextBox.Text);
    inv.Price = decimal.Parse(addPriceTextBox.Text);
    inv.Description = addDescriptionTextBox.Text;

    db.tbl_Inventories.InsertOnSubmit(inv);
    db.SubmitChanges();

    int id = inv.IdProducts;

    MessageBox.Show($"Item creation successful. Item number is {id}");
}

我不断收到以下错误:

当IDENTITY_INSERT设置为OFF时,无法在表'tbl_Inventory'中为标识列插入显式值

我的表有一个称为的列IDProducts,用作以1为增量的标识列。我可以在Visual Studio设计窗口中添加条目,并且它添加的条目没有错误且增量正确运行,但是在运行代码时却没有。关键是我的代码没有尝试为分配值IDProducts我尝试删除IDProducts并将其添加回去,但是仍然出现相同的错误。我还有一个通过Visual Studio创建的另一张表,使用的代码与上面的代码非常相似,这与向表中添加条目的代码非常相似,并且没有任何问题。我不确定我可能会做些什么。

Questioner
Nolan Melhart
Viewed
11
marc_s 2020-11-28 15:58:31

似乎你的C#模型类未正确将IDProducts定义IDENTITY列-因此,你的Linq-to-SQL代码想将一个值插入到identity列中,这会导致此错误。

你需要确保正确注释你的专栏-由于我不知道你的tbl_Inventory班级是什么样子,因此我只能向你显示以下内容:

[Table(Name="Inventory")]     // or whatever it really is ...
public class tbl_Inventory   
{
    [Column(IsPrimaryKey=true,IsDbGenerated=true)]
    public int IDProducts { get; set; }

    // all your other columns here
}  

你需要将IsDbGenerated注释添加到你的IDProducts列中,以便Linq-to-SQL知道这是一列,数据库在插入时会在其中生成值。