简体   繁体   中英

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

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#

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

Since your column FOO_ID is an auto-increment IDENTITY column, you must omit it from your INSERT statement. 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,这样会强制自动增量设置正确的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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