Click here to Skip to main content
15,900,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I currently have a ASP.NET web application that captures the users input and puts it into a database.

I have two tables 'Stock_Take' and 'Stock_Take_Item', Stock_Take stores the information of the user who submitted the values and the date of the stock take and the stock_take_item stores the information of the Item ID, Item Description, and the Quantity regarding each item.

The primary key of Stock_Take is StockTakeIDNew and auto increments using 'Identity'and is a foreign key in the Stock_Take_Item table.

As I insert all the information from the Stock Take (on a click of a button) i only insert the username and date into Stock_Take and the primary key auto increments. However this does not affect the foreign key in the Stock_Take_Item table, therefore i cannot relate the two tables.

Any idea how i go about this?

Here's my C# code with the SQL Inserts included:
protected void btnSubmit_Click(object sender, EventArgs e)
       {
       string query = "insert into Stock_Take_Item(ItemID, BarQuantity, StorageQuantity) values(@ID, @BAR, @STORAGE); insert into Stock_Take(Username, StockDate)" +
           " values(@Username, GetDate())";
       SqlConnection con = new SqlConnection(connectionString);
       SqlCommand cmd = new SqlCommand(query, con);
       con.Open();

       foreach (GridViewRow row in gvStockTake.Rows)
       {
           Label ID = row.FindControl("itemId") as Label;
           TextBox BAR = row.FindControl("txtBar") as TextBox;
           TextBox STORAGE = row.FindControl("txtStorage") as TextBox;
           cmd.Parameters.Clear();
           cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID.Text;
           cmd.Parameters.Add("@BAR", SqlDbType.Int).Value = BAR.Text;
           cmd.Parameters.Add("@STORAGE", SqlDbType.Int).Value = STORAGE.Text;

       }
       cmd.Parameters.AddWithValue("@Username", Session["username"]);
       cmd.ExecuteNonQuery(); //query execution
       con.Close();
       Response.Write("Successfully inserted stock take items.");
   }


I'm still learning ASP.NET C# and SQL as i go, so any recommendations are more than appreciated!!

What I have tried:

I've tried to research this but could not find the right result.
Posted
Updated 11-Apr-18 23:11pm
Comments
F-ES Sitecore 12-Apr-18 4:21am    
You have two tables so you need to do to inserts. Insert into the parent table (stock_take) first and get the ID of the new record

https://stackoverflow.com/questions/18373461/execute-insert-command-and-return-inserted-id-in-sql?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

now you have the ID you can use that ID when you are inserting into the child Stock_Take_Item table to relate the two together.

1 solution

The idea of a Foreign Key is that it relates multiple rows to data in a different table. For example, think of an invoice. It consists of invfo with is relevant to the whole invoice, like the Invoice number and the date it was issued, and a set of rows for each item purchased:
Invoice number: 12345
Invoice Date:   12/04/2018
Customer:       Joe's Shoes, Shoe House, Shoe Lane, Shoeton

Qty    Desc                 Price Per     Total
1      Laces                    $5.00     $5.00
2      Shoe polish              $7.00    $14.00
To store this, you set up tables:
Invoices
ID           PRIMARY KEY
InvoiceNumber
Date
CustomerID
InvoiceLines
ID           PRIMARY KEY
InvoiceID    FOREIGN KEY to Invoices.ID
ItemsCount
Description
Price
You create the Invoices item first, then use the ID to set the value of the Foreign Key for each row of the InvoiceLines table.
This doesn't happen automatically - you pick up the Invoices.ID value from the DB after you insert a row, normally by using the @@IDENTITY or SCOPE_IDENTITY value: @@IDENTITY (Transact-SQL) | Microsoft Docs[^]. Normally, the whole set of INSERT operations would be contained in a TRANSACTION to ensure database integrity if there is a problem.

Personally, I prefer to use GUID based IDs instead of IDENTITY, and assign the ID value from the presentation software instead of relying on incrementing values - if nothing else, it does not imply any order or lack of "gaps" which IDENTITY does (and shouldn't be used for)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900