主键,外键会话()C#.net如何使用Session();

时间:2015-10-27 20:44:06

标签: c# .net sql-server

我坚持这个问题几个小时。我需要帮助

我尝试将这个主键在一个表中的密钥传输到另一个表,这将是外键

使用

int userID = Convert.ToInt32(Session["id"]);

从此表格

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication6
{
    public partial class WebForm8 : System.Web.UI.Page
    {
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);

            SqlCommand objcmd = new SqlCommand("Select * from dbo.UserLoggins where UserName='" + args.Value + "'", con);
            SqlDataReader objReader;
            con.Open();
            objReader = objcmd.ExecuteReader();

            if (objReader.HasRows)
            {
                args.IsValid = false;
                Label2.Visible = true;
                Label2.Text = "You must log in before, please click 'log in' and log in";
                HyperLink3.Visible = true;
            }
            else
            {
                args.IsValid = true;
            }
            con.Close();
        }

        // here
        protected void RegisterUser(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            String a = txtUsername.Text;
            String b = txtPassword.Text;
            String b2 = txtConfirmPassword.Text;
            String c = txtEmail.Text;
            String LastName = TxtLastName.Text;
            String FirstName = TxtFirstName.Text;
            String PhoneNumber = TxtPhoneNumber.Text;
            int ID = -1;

            //http://www.aspnettutorials.com/tutorials/advanced/use-md5-to-encrypt-passwords-with-asp-net-4-0-and-c/

            //create the MD5CryptoServiceProvider object we will use to encrypt the password
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            //create an array of bytes we will use to store the encrypted password
            Byte[] hashedBytes;
            //Create a UTF8Encoding object we will use to convert our password string to a byte array
            UTF8Encoding encoder = new UTF8Encoding();

            //encrypt the password and store it in the hashedBytes byte array
            hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(txtPassword.Text));

            String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);

            SqlCommand command = new SqlCommand(@"INSERT INTO [dbo].[UserLoggins] (UserName,Email,PassWord,LastName,FirstName,PhoneNumber)
                VALUES (@UserName, @Email, @Password,@LastName, @FirstName, @PhoneNumber);" + "select scope_Identity() as ID", con);
            command.Parameters.AddWithValue("@UserName", a);
            command.Parameters.AddWithValue("@Email", c);
            command.Parameters.AddWithValue("@Password", hashedBytes);
            command.Parameters.AddWithValue("@LastName", LastName);
            command.Parameters.AddWithValue("@FIrstName", FirstName);
            command.Parameters.AddWithValue("@PhoneNumber", PhoneNumber);

            con.Open();
            SqlDataReader rd = command.ExecuteReader();

            while (rd.Read())
            {
                ID = int.Parse(rd["ID"].ToString());
            }

            rd.Close();
            con.Close();

            Session.Add("UserLogginID", ID);

            //con.Open();
            //command.ExecuteScalar();
            //ID = (int)(decimal)command.ExecuteScalar();
            //con.Close();
            Label1.Visible = true;
            Label1.Text = "非常感謝你 (fēicháng gǎnxiè nǐ), Please Proceed to Customersinfo page";
            //Button2.Visible = true;
            Panel2.Visible = false;
            Panel1.Visible = true;
            HyperLink1.Visible = true;
            HyperLink2.Visible = true;
            ResetAll();
        }

        private void ResetAll()
        {
            txtUsername.Text = "";
            txtPassword.Text = "";
            txtConfirmPassword.Text = "";
            txtEmail.Text = "";
        }
    }
}

到此表格

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication6.Utilities;

namespace WebApplication6
{
    public partial class WebForm12 : System.Web.UI.Page
    {
        protected void Button_Submit_Click(object sender, EventArgs e)
        {
            string Address = TxtBox_Address.Text;
            string City = TxtBox_City.Text;
            string State = TxtBox_State.Text;
            string zip = Txt_Zip.Text;
            string Country = TxtBox_Country.Text;

            int userID = Convert.ToInt32(Session["id"]);

            String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO ShipppingAddress (AddressLine1,City,State,Zip,UserLogginID,Country) VALUES (@AL,@City,@State,@Zip,@UL,@Country)";

            cmd.Parameters.AddWithValue("@AL", Address);
            cmd.Parameters.AddWithValue("@City", City);
            cmd.Parameters.AddWithValue("@State", State);
            cmd.Parameters.AddWithValue("@Zip", zip);
            cmd.Parameters.AddWithValue("@UL", userID);
            cmd.Parameters.AddWithValue("@Country", Country);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
  }
}

然而,出现了这个错误:

  

INSERT语句与FOREIGN KEY约束冲突" FK_ShipppingAddress_UserLoggins"。冲突发生在数据库" KazuTest",table" dbo.UserLoggins",column' UserLogginID'。

我该如何解决这个问题?

非常感谢你。

1 个答案:

答案 0 :(得分:0)

您在每种方法中使用不同的会话变量:

Session.Add("UserLogginID", ID);

int userID = Convert.ToInt32(Session["id"]);

Convert.ToInt32null对象中传递时将返回0,而投射会抛出异常。

您也可以解决一些拼写错误:

UserLogginID --> UserLoginID
ShipppingAddress --> ShippingAddress 
UserLoggins --> UserLogins