简体   繁体   English

无法使用自动增量插入到SQL Server CE

[英]Cannot insert to SQL Server CE with autoincrement

I am unable to insert new row to a SQL Server CE 3.5 table due to an auto-increment column 由于自动增量列,我无法将新行插入SQL Server CE 3.5表

My schema is as simple as: 我的架构很简单:

@"CREATE TABLE DataTable ("Foo_ID int PRIMARY KEY IDENTITY, " +
                          "FooName NVARCHAR(200) NOT NULL)

And my insert statement in C# 我在C#中的insert语句

SqlCeCommand cmd = new SqlCeCommand(@"INSERT INTO DataTable VALUES(@Foo_ID, @FooName)", con))
conn.Open();
cmd.Parameters.Add(new SqlCeParameter("FooName", "test123"));
cmd.ExecuteNonQuery();

Then I get the error: 然后我得到错误:

System.IndexOutOfRangeException: An SqlCeParameter with ParameterName 'Foo_ID' is not contained by this SqlCeParameterCollection System.IndexOutOfRangeException:此SqlCeParameterCollection不包含具有ParameterName'Foo_ID'的SqlCeParameter

Since your column FOO_ID is an auto-increment IDENTITY column, you must omit it from your INSERT statement. 由于列FOO_ID是自动递增IDENTITY列,因此必须从INSERT语句中省略它。 As such, you need to explicitly specify the list of columns you want to insert values into - try this: 因此,您需要显式指定要插入值的列的列表 - 试试这个:

SqlCeCommand cmd = new SqlCeCommand(@"INSERT INTO DataTable(FooName) VALUES(@FooName)", con))
conn.Open();
cmd.Parameters.Add(new SqlCeParameter("FooName", "test123"));
cmd.ExecuteNonQuery();

问题是你的参数中有@Foo_ID作为查询,但不要在cmd.Parameters.Add添加这样的参数。

尝试发送-1作为ID,这样会强制自动增量设置正确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM