[英]How to insert data into multiple tables using a POST request on Postman?
我有3個表格需要填充; OrderHistory,OrderHistoryItem和OrderHistoryLabel。 這三個表通過以下鍵相互連接:
UserID - references AspNetUsers(Id)
OrderID in OrderHistoryItem - references OrderHistory(OrderID)
這張圖片將提供有關表格的更多信息,但是我只包括了我認為現階段重要的內容。
以下代碼是在Visual Studio中編寫的,表示通過在表中添加所有需要的值來創建訂單的方法。
[Route("v1/orderhistory")]
[HttpPost()]
public IActionResult CreateOrder([FromBody]OrderHistoryDto ohdata, [FromBody]OrderHistoryItemDto itemdata, [FromBody]HistoryLabelDto labeldata)
{
try
{
if (ohdata == null) throw new ArgumentException("No data specified");
if (itemdata == null) throw new ArgumentException("No data specified");
if (labeldata == null) throw new ArgumentException("No data specified");
//string orderId = "40281804-FE51-4893-AEA8-944903C27771";
var orderID = Guid.NewGuid();
using (var con = _connFactory())
{
con.Open();
con.Execute("INSERT INTO dbo.OrderHistoryItemLabel (LabelID, OrderProductID) VALUES (@labelID, @orderProductID)", new
{
labeldata.orderProductID,
labeldata.labelID
});
con.Execute(@"INSERT INTO dbo.OrderHistoryItem (ProductID, OrderID, ProductGroup, NormalPrice, Price, StandardUnit, PricePerStandardAmount, Quantity, Discount, IsDiscounted, TotalPrice)
VALUES (@productID, @orderID, @productGroup, @normalPrice, @price, @standardUnit, @pricePerStandardAmount, @quantity, @discount, @isDiscounted, @totalPrice)", new
{
itemdata.productID,
itemdata.orderID,
itemdata.productGroup,
itemdata.normalPrice,
itemdata.price,
itemdata.standardUnit,
itemdata.pricePerStandardAmount,
itemdata.quantity,
itemdata.discount,
itemdata.isDiscounted,
itemdata.itemTotalPrice,
labeldata.orderProductID
});
con.Execute("INSERT INTO dbo.OrderHistory (UserID, TransferredAtUtc, OrderTotalPrice, StoreID) VALUES (@userID, @transferredAtUtc, @orderTotalPrice, @storeID)", new
{
ohdata.userID,
ohdata.transferredAtUtc,
ohdata.orderTotalPrice,
ohdata.storeID
});
}
return Ok(orderID);
}
catch (Exception exc)
{
return BadRequest();
}
}
}
作為測試工具,我使用的是Postman,而用JSON編寫的POST請求如下:
{
"TransferredAtUtc": "",
"OrderTotalPrice": 344343.43,
"StoreId": 1,
"Items": [
{
"LabelID": [
1,
2,
3,
4,
5
],
"ProductID": 1,
"ProductGroup": "asd",
"NormalPrice": 2,
"Price": 2,
"StandardUnit": "asd",
"PricePerStandardAmount": 2,
"Quantity": 1,
"Discount": 0,
"IsDiscounted": 0,
"ItemTotalPrice": 2
},
{
"LabelID": [
1,
2,
5
],
"ProductID": 434,
"ProductGroup": "asd",
"NormalPrice": 2,
"Price": 22,
"StandardUnit": "asd",
"PricePerStandardAmount": 2,
"Quantity": 1,
"Discount": 0,
"IsDiscounted": 0,
"ItemTotalPrice": 2
}
]
}
]
我幾乎不了解如何使用JSON編寫代碼,所以我很想征詢您的建議,因為每次發送請求時,方法開頭的if()
子句都會把我拒之門外。 問題似乎是沒有填充值,所以我的猜測是我編寫的JSON代碼未正確編寫。 有小費嗎?
在我看來,我將OrderHistoryDto OrderHistoryItemDto和HistoryLabelDto組合成一個模型,例如CreatedOrder,其中將包含這三個項目。 這樣,您只有一個項目通過身體傳遞,並且您仍然可以輕松訪問這三個項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.