3

ユーザーが「カテゴリ」と「アイテム」を送信する2つのフォームフィールドがあります。

次のコードはカテゴリを正常に挿入します(WebMatrixイントロPDFから変更しました)が、「item」をItemsテーブルに挿入する方法がわかりません。また、新しいカテゴリのIDを新しいアイテム行に追加する必要があります。

これはこれまでに機能しているコードです

@{ 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"));
}
}
}

これは答えるのが非常に簡単な質問だと思います/期待しているので、これ以上の詳細は必要ないことを願っていますが、ある場合はお知らせください。ありがとう。

4

1 に答える 1

4

最後に挿入されたレコードの ID を返す WebMatrix 内に Database.GetLastInsertId メソッドがあります (使用している IDENTITY 列であると仮定します)。それを使用します:

db.Execute(insertQuery, Category);
var id = (int)db.GetLastInsertId(); //id is the new CategoryId
db.Execute(secondInsertQuery, param1, id);
于 2010-08-16T22:22:38.750 に答える