IDENTITY INSERT and LINQ to SQL(身份插入和 LINQ to SQL)
问题描述
我有一个 SQL Server 数据库.该数据库有一个名为 Item 的表.项目有一个名为ID"的属性.ID 是我桌子上的主键.此主键是一个增量值为 1 的 int.当我尝试插入记录时,我收到一条错误消息:
I have a SQL Server database. This database has a table called Item. Item has a property called "ID". ID is the primary key on my table. This primary key is an int with an increment value of 1. When I attempt to insert the record, I receive an error that says:
当 IDENTITY_INSERT 设置为 OFF 时,无法为表 'Item' 中的标识列插入显式值.".
Cannot insert explicit value for identity column in table 'Item' when IDENTITY_INSERT is set to OFF.".
我正在尝试使用以下代码插入记录:
I am attempting to insert records using the following code:
public int AddItem(Item i)
{
try
{
int id = 0;
using (DatabaseContext context = new DatabaseContext())
{
i.CreatedOn = DateTime.UtcNow;
context.Items.InsertOnSubmit(i);
context.SubmitChanges();
id = i.ID;
}
return id;
}
catch (Exception e)
{
LogException(e);
}
}
当我在提交之前查看 i.ID 时,我注意到 i.ID 设置为 0.这意味着我试图插入 0 作为身份.但是,我不确定它应该是什么.有人可以帮我吗?
When I look at i.ID before submitting it, I notice that i.ID is set to 0. Which would imply that I'm trying to insert 0 as the identity. However, I'm not sure what it should be. Can someone help me out?
谢谢!
推荐答案
听起来好像您的模型没有意识到它是一个身份;ID
列应标记为 db-generated(Auto Generated Value
在 UI 中,或 IsDbGenerated
在 xml 中),并且可能作为首要的关键.然后它不会尝试插入它,并在写入后正确更新值.
It sounds simply as though your model is unaware of the fact that it is an identity; the ID
column should be marked as db-generated (Auto Generated Value
in the UI, or IsDbGenerated
in the xml), and probably as the primary key. Then it will not attempt to insert it, and will update the value correctly after it is written.
这篇关于身份插入和 LINQ to SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:身份插入和 LINQ to SQL


基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01