首页 > 解决方案 > 使用 C# 时出现错误“无法在表中插入标识列的显式值”

问题描述

我遇到了一个简单的本地 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 创建了另一个表,其方式与上面的代码非常相似,将条目添加到表中,我没有任何问题。我不确定我可能会做些什么不同的事情。

标签: c#sql-serverlinq-to-sql

解决方案


看起来好像您的 C# 模型类没有将列正确定义IDProductsIDENTITY列 - 因此您的 Linq-to-SQL 代码尝试将值插入标识列,这会导致此错误。

您需要确保正确注释您的专栏 - 因为我不知道您的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 在插入时知道这是由数据库生成值的列。


推荐阅读