Having read around this site I thought the following code would return the ID of the item I add to my database but the int value I am trying to fill isn’t showing up in scope. Here is the code for my insert statement:
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;
}
}
}
The database is updated with the Weight Exercise details. I have checked when debugging and the command parameter @ID holds the ID of the latest entry. Int ID does not show up in locals when debugging and if I Watch it I get:
ID The name 'ID' does not exist in the current context
What am I doing wrong here?
This indicates the database code you are currently using is functioning fine.
This is the root of your question. The problem is that you’ve scoped ID to inside the
block. Outside of that block, the identifier
IDhas no meaning.Declare
IDat the top of the scope for this procedure and you should be able to see it in Locals or add a Watch.