我正在使用以下查询来插入一行,我插入了行,但我希望获得主键以返回插入。行已成功插入,但获取主键给我带来了困难。一切顺利,但在lastID = Convert.ToInt32(Id.Value);
它说InvalidCastException。问题“Getting primary key or any other attribute just after inserting a row”也与此问题有关
注意:主键列名是“Id”,它是int类型,我在asp.net中这样做
SqlParameter Id =new SqlParameter("Id" , SqlDbType.Int);
Id.Direction = ParameterDirection.Output;
//conn.Open();
//int inserted = 0;
//int lastID = 0;
string insertOffer = "INSERT INTO Offers (userId, column1, column2, column3)
VALUES (SomeINT, 'abc', 'abc', 'abc');select Id=SCOPE_IDENTITY()";
int lastID = 0;
using (SqlConnection conn = new SqlConnection(Connection))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(insertOffer, conn))
{
comm.Parameters.Add(Id);
comm.ExecuteNonQuery();
lastID = Convert.ToInt32(Id.Value);
}//end using comm
}//end using conn