System.Data.SqlClient.SqlException occurred HResult=0x80131904 Message=Cannot insert explicit value for identity column in table 'DriversDetailsTable' when IDENTITY_INSERT is set to OFF. Source=.Net SqlClient Data Provider StackTrace: <Cannot evaluate the exception stack trace>
我在运行代码时遇到上述错误,不知道为什么。这是我的代码:
SqlConnection conn = new SqlConnection(@"Data Source = ComputerName\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;");
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand($@"INSERT INTO DriversDetailsTable (name, Id, DateJoined) VALUES ('Driver4', 1, '2017-07-06')", conn);
command.ExecuteNonQuery();
conn.Close();
答案 0 :(得分:3)
是的,这是因为您的Id
列是IDENTITY
列,因此您应该在INSERT
语句中省略它,如下所示。由于它是一个IDENTITY
列,因此您无法为其明确插入值,除非您将IDENTITY_INSERT
设置为OFF
但不认为您不想这样做
INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06')
SideNote:当您使用硬编码/静态值时,没有看到字符串插值$@"INSERT
的C#6语法的原因
答案 1 :(得分:2)
据推测,Id
是IDENTITY
列。因此,您不应尝试INSERT
进入Id
列 - 从INSERT
语句中省略它,并让数据库告诉您什么号码已分配:
SqlCommand command = new SqlCommand($@"
INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06');
SELECT SCOPE_IDENTITY();", conn);
并使用ExecuteScalar()
来获取值:
int id = (id)(decimal)command.ExecuteScalar();
(有关演员的解释,请参阅Why does select SCOPE_IDENTITY() return a decimal instead of an integer?)
其他选择:
IDENTITY
列答案 2 :(得分:0)
如果您确实希望能够出于某种原因插入ID,则需要将IDENTITY_INSERT
设置为ON
,如下所示:
Set Identity_Insert DriverDetailsTable ON;
这可以针对特定命令执行,如下所示:
SqlCommand command = new SqlCommand($@"
Set Identity_Insert DriverDetailsTable ON;
INSERT INTO DriversDetailsTable (name, Id, DateJoined) VALUES ('Driver4', 1, '2017-07-06');
Set Identity_Insert DriverDetailsTable OFF;", conn);