我的代码需要一些帮助。如何让 scope_Identiy 将 ImageId 存储为会话变量。我已经坚持了很长时间,但我无法让它发挥作用。
编辑:我相信从 SqlDataReader dataReader = cmd.ExecuteReader(); 下来是错误的。我只是不知道如何解决它。我对此还是陌生的。
protected void btnAddImage_Click(object sender, EventArgs e)
{
//store items in session variables
Session["AnimalName"] = AnimalNameTextBox.Text;
Session["TypeOfAnimal"] = TypeofAnimalDDL.Text;
Session["Breed"] = BreedTextBox.Text;
Session["CrossBreed"] = CrossBreedAddDDL.Text;
Session["Sex"] = SexDDL.Text;
Session["Size"] = SizeDDL.Text;
Session["Age"] = AgeDDL.Text;
Session["Location"] = LocationAddDDL.Text;
Session["Date"] = DateTextBox.Text;
Session["Contact"] = ContactTextBox.Text;
Session["Children"] = ChildrenDDL.Text;
Session["OtherCats"] = OtherCatsDDL.Text;
Session["OtherDogs"] = OtherDogsDDL.Text;
Session["Neutered"] = NeuteredDDL.Text;
Session["Microchipped"] = MicrochippedDDL.Text;
Session["Colour"] = ColourTextBox.Text;
Session["IndoorOutdoor"] = IndoorOutdoorDDL.Text;
Session["Details"] = DetailsTextBox.Text;
string s_Image_Name = txt_Image_Name.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
int newImageID ;
byte[] n_Image_Size = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Posted_Image = FileUpload1.PostedFile;
Posted_Image.InputStream.Read(n_Image_Size, 0, (int)FileUpload1.PostedFile.ContentLength);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Images(Name,[Content],Size,Type) VALUES (@Image_Name,@Image_Content,@Image_Size,@Image_Type); SELECT ImageID = SCOPE_IDENTITY ()";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlParameter Image_Name = new SqlParameter("@Image_Name", SqlDbType.VarChar, 500);
Image_Name.Value = txt_Image_Name.Text;
cmd.Parameters.Add(Image_Name);
SqlParameter Image_Content = new SqlParameter("@Image_Content", SqlDbType.Image, n_Image_Size.Length);
Image_Content.Value = n_Image_Size;
cmd.Parameters.Add(Image_Content);
SqlParameter Image_Size = new SqlParameter("@Image_Size", SqlDbType.BigInt, 99999);
Image_Size.Value = FileUpload1.PostedFile.ContentLength;
cmd.Parameters.Add(Image_Size);
SqlParameter Image_Type = new SqlParameter("@Image_Type", SqlDbType.VarChar, 500);
Image_Type.Value = FileUpload1.PostedFile.ContentType;
cmd.Parameters.Add(Image_Type);
SqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows)
{
dataReader.Read();
newImageID = Convert.ToInt32(dataReader["ImageID"]);
}
dataReader.Close();
}