【问题标题】:C# Insert Value Foreign KeyC# 插入值外键
【发布时间】:2018-10-24 05:51:45
【问题描述】:

我有 2 个表,即 tableCustomerLogin 和 tableCustomerRegister。 tableCustomerLogin 有外键,即 cust_id

在tableCustomerLogin中,我有tableCustomerLogin

    cust_login_id
    cust_id
    cust_email
    cust_username
    cust_password

对于 tableCustomerRegister,

    tableCustomerRegister
    cust_id
    cust_fullname
    cust_username
    cust_email
    cust_password
    cust_mobile_number
    cust_image
    cust_address1
    cust_address2
    cust_city
    cust_postcode
    cust_create_acc_time

当客户注册时,数据将存储在表CustomerRegister中。如何让它在 tableCustomerLogin 中注册?

string sql = @"INSERT INTO tableCustomerRegister VALUES (@cust_fullname, @cust_username, @cust_email, @password, @cust_mobile_phone, @cust_address1, @cust_address2, @cust_image, @cust_city, @cust_state, @cust_postcode, @cust_create_acc_time, @role, @enabled)";

            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@cust_fullname", txtFirstName.Text + " " + txtLastName.Text);
            cmd.Parameters.AddWithValue("@cust_username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@cust_email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@password", passwordhash);
            cmd.Parameters.AddWithValue("@cust_mobile_phone", txtMobilePhone.Text);
            cmd.Parameters.AddWithValue("@cust_address1", txtAddress1.Text);
            cmd.Parameters.AddWithValue("@cust_address2", txtAddress2.Text);
            cmd.Parameters.AddWithValue("@cust_image", txtProfilePicture.Text);
            cmd.Parameters.AddWithValue("@cust_city", ICityString());
            cmd.Parameters.AddWithValue("@cust_state", ddState.SelectedValue.ToString());
            cmd.Parameters.AddWithValue("@cust_postcode", txtPostcode.Text);
            cmd.Parameters.AddWithValue("@cust_create_acc_time", DateTime.Now);
            cmd.Parameters.AddWithValue("@role", "user");
            cmd.Parameters.AddWithValue("@enabled", enabled);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                lblStatus.Text = "Status: Data successfully saved.";
            }

【问题讨论】:

  • 尝试为tableCustomerLogin添加另一个“INSERT”子句,并在tableCustomerRegister中插入值后调用它。
  • 首先,为什么还要在tableCustomerLogin表中插入相同的数据呢?这是外键出现的情况,并且您已经在表中使用了它。您可以使用外键关系映射表。
  • 当用户想登录时,我只会调用tableCustomerLogin。 @KamalaHB

标签: c# sql ado.net


【解决方案1】:

嗯,首先你需要改变你的查询

string sql = @"INSERT INTO tableCustomerRegister  OUTPUT INSERTED.cust_id VALUES (@cust_fullname, @cust_username, @cust_email, @password, @cust_mobile_phone, @cust_address1, @cust_address2, @cust_image, @cust_city, @cust_state, @cust_postcode, @cust_create_acc_time, @role, @enabled)";
 SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.AddWithValue("@cust_fullname", txtFirstName.Text + " " + txtLastName.Text);
        cmd.Parameters.AddWithValue("@cust_username", txtUsername.Text);
//so on (all your parameters)
var custid  = (int)cmd.ExecuteScalar()

ExecuteScalar return int,在这种情况下它将返回cust_id,因为您的查询有OUTPUT INSERTED.cust_id。现在您已将插入的cust_id 保存在tableCustomerRegister 中。现在,您只需编写另一个查询,使用外键 cust_id 将数据保存到您的 tableCustomerLogin 中。像这样,

string Sql2 = "INSERT INTO tableCustomerLogin (column_names) VALUES (parameters values)";
SqlCommand cmd = new SqlCommand(sq2, conn);
cmd.Parameters.AddWithValue("@cust_id",custid);  //as foreign key
//all other Parameters

【讨论】:

    【解决方案2】:

    您可以先insert 一个tableCustomerRegister 记录,然后insert 另一个数据tableCustomerLogin 表。您最好在 transaction 块中执行此操作。

    另一种方式,您可以将trigger 添加到tableCustomerLogin 表中。

    CREATE TRIGGER trg_tableCustReg ON tableCustomerRegister
    FOR INSERT
    AS   
      /*
       *  if CustLoginID is a identity , no dont need to add  
       */ 
        INSERT INTO tableCustomerLogin 
                (cust_login_id, cust_id, cust_email, cust_username, cust_password)
            Select
                'CustLoginID', 
                cust_id , 
                cust_email, 
                cust_username, 
                user_password
                FROM inserted
    
    go
    

    【讨论】:

      【解决方案3】:

      可能最好的解决方案是遵循 DRY 原则,不要重复自己。

      例如,我认为您可以将所有信息存储在单个表 customer_table 中,然后使用更简单的逻辑仅从该表中检索必要的数据。

      相反,如果您想保留实际的数据结构,只需在 first 后添加新的插入语句,用分号分隔

      how to insert data into multiple tables at once

      【讨论】:

        【解决方案4】:

        有两种不同的方式。你应该使用SCOPE_IDENTITY

        string sql = @"INSERT INTO tableCustomerRegister VALUES (@cust_fullname, @cust_username, @cust_email, @password, @cust_mobile_phone, @cust_address1, @cust_address2, @cust_image, @cust_city, @cust_state, @cust_postcode, @cust_create_acc_time, @role, @enabled) SELECT SCOPE_IDENTITY()";
        

        SCOPE_IDENTITY 返回插入到 同一范围内的标识列

        var newId= cmd.ExecuteScaler();
        

        newId 为您创建了新的主键 ID cust_id

        你有这个ID(cust_id),你可以在登录表中注册。

        INSERT INTO  tableCustomerLogin (cust_login_id,**cust_id**,cust_email,cust_username,cust_password)
        
        
        cust_id = newId 
        

        【讨论】:

        • 你能解释更多吗?
        【解决方案5】:

        如果在 tableCustomerRegister 表中自动创建 Cust_id,那么您可以在 tableCustomerLogin 表中保存相同的 id (cust_id)。那么只有你的外键关系起作用。

             try
                            {
                                conn.Open();
                                cmd.ExecuteNonQuery();
                                SqlCommand get_custid_cmd = new SqlCommand("select @@identity", conn);
                                int cust_id = Convert.ToInt32(get_custid_cmd.ExecuteScalar());
                                string sql_insert = @"INSERT INTO tableCustomerLogin VALUES (@cust_id, @cust_username, @cust_email, @password)";
        
                        SqlCommand cmd_insert = new SqlCommand(sql_insert, conn);
                        cmd_insert.Parameters.AddWithValue("@cust_id",cust_id);
                        cmd_insert.Parameters.AddWithValue("@cust_username", txtUsername.Text);
                        cmd_insert.Parameters.AddWithValue("@cust_email", txtEmail.Text);
                        cmd_insert.Parameters.AddWithValue("@password", passwordhash);
                        cmd_insert.ExecuteNonQuery();
                                    lblStatus.Text = "Status: Data successfully saved.";
        
                            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-20
          • 2012-09-17
          • 1970-01-01
          • 2020-02-28
          • 1970-01-01
          • 2021-12-31
          相关资源
          最近更新 更多