在阅读了这个网站后,我认为以下代码将返回我添加到数据库中的项目的 ID,但我试图填充的 int 值没有显示在范围内。这是我的插入语句的代码:
foreach (ExOb exc in exobject)
{
Type type = exc.GetType();
//Add a weight exercise
if (type == typeof(Weights))
{
Weights thisweight = (Weights)exc;
string InsertWeight = ("INSERT INTO WeightExercise (ExcerciseName, Duration, Sets, DiaryId) VALUES (@name, @time, @sets, @DiaryId) SET @ID = SCOPE_IDENTITY();");
com = new SqlCommand(InsertWeight, con);
com.Parameters.AddWithValue("@name", thisweight.ExcerciseName);
com.Parameters.AddWithValue("@time", thisweight.WeightDuration);
com.Parameters.AddWithValue("@sets", thisweight.TotalSets);
com.Parameters.AddWithValue("@DiaryId", results[0]);
com.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
con.Open();
com.ExecuteNonQuery();
int ID = (int)com.Parameters["@ID"].Value;
con.Close();
}
else if (type == typeof(Cardio))
{
Cardio thiscardio = (Cardio)exc;
}
}
}
数据库已更新为体重锻炼详细信息。我在调试时检查过,命令参数@ID 包含最新条目的ID。调试时,Int ID 不会显示在本地,如果我观看它,我会得到:
ID The name 'ID' does not exist in the current context
我在这里做错了什么?