c# - 使用 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# 模型类没有将列正确定义IDProducts
为IDENTITY
列 - 因此您的 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 在插入时知道这是由数据库生成值的列。
推荐阅读
- android - 在 Android Studio 中添加外部库作为文件导致依赖错误
- dart - 如何在颤动中获取资产的文件路径?
- rest - HTTP PUT 不一定将新记录添加到后端
- ruby-on-rails - form_for 助手给了我一个错误,尽管它在那里
- libgdx - 粒子发射器的数量会影响性能吗?
- python-2.7 - 安装 tensorflow 时出现“没有名为队列的模块”
- identityserver4 - IdentityServer4 - 有没有办法在授权代码流中静默地对用户进行身份验证?
- java - Java 等到使用 Selenium 加载页面
- python - 如果我在 matplotlib 中有图形(或轴)列表,如何创建多个图?
- azure - Microsoft Azure 流分析和 Blob 存储输入