SQL to insert data into multiple tables with one POST in Razor WebMatrix syntax

I have two form fields from which the user submits a "category" and an "element".

The following code inserts a category tone (I changed it from the embedded WebMatrix PDF file), but I have no idea how to insert an “element” into the “Items” table. I also need to add the id of the new category to the new row.

This is the code that still works.

@{ var db = Database.OpenFile("StarterSite.sdf");
var Category = Request["Category"]; //was name
var Item = Request["Item"]; //was description
if (IsPost) {
// Read product name.
Category = Request["Category"];
if (Category.IsEmpty()) {
Validation.AddFieldError("Category", "Category is required");
}
// Read product description.
Item = Request["Item"];
if (Item.IsEmpty()) {
Validation.AddFieldError("Item",
"Item type is required.");
}
// Define the insert query. The values to assign to the
// columns in the Products table are defined as parameters
// with the VALUES keyword.
if(Validation.Success) {
var insertQuery = "INSERT INTO Category (CategoryName) " +
"VALUES (@0)";
db.Execute(insertQuery, Category);
// Display the page that lists products.
Response.Redirect(@Href("~/success"));
}
}
}

I guess / hope this is a very simple question to answer, so I hope no more details are required - but please let me know if there is any. Thank.

+3
1

WebMatrix Database.GetLastInsertId, ( , IDENTITY). :

db.Execute(insertQuery, Category);
var id = (int)db.GetLastInsertId(); //id is the new CategoryId
db.Execute(secondInsertQuery, param1, id);
+4

Source: https://habr.com/ru/post/1759963/


All Articles