我有我的SQL Server CE數據庫如下表:從父表到子表的主鍵的應用
訂單
OrderID (handled my DBMS)
CustomerID
OrderDate
ORDER_DETAILS
OrderID (from the ORDERS table)
ProductID
OrderQTY
我目前使用2個插入查詢將新訂單添加到數據庫。第一個將訂單插入到ORDERS
表中並允許DBMS創建OrderID
,第二個將OrderID
用於插入到ORDER_DETAILS
表中。
我在下面使用的方法看起來很klunky,並且可能容易出現併發問題。當新記錄插入到ORDERS
表中時,是否有辦法讓DBMS處理爲ORDER_DETAILS
表創建正確的OrderID
?
這是我用來運行插入查詢C#:
public int InsertOrder(Order order)
{
DBConnection connection = DBConnection.getInstance();
connection.conn.Open();
using (SqlCeCommand query = new SqlCeCommand(OrderCommandList.cmdInsertOrderHeader, connection.conn))
{
query.Parameters.AddWithValue("@CustomerID", order.CustomerID);
query.Parameters.AddWithValue("@OrderDate", order.OrderDate);
query.ExecuteNonQuery();
}
//retrieves the PK for the recently inserted record
int newOrderPK = 0;
using(SqlCeCommand cmdGetIdentity = new SqlCeCommand("SELECT @@IDENTITY", connection.conn))
{
newOrderPK = Convert.ToInt32(cmdGetIdentity.ExecuteScalar());
}
connection.conn.Close();
InsertOrderDetails(order, newOrderPK);
return newOrderPK;
}
//inserts all the order details associated with the Order object
private void InsertOrderDetails(Order order, int orderForeignKey)
{
foreach (OrderDetail od in order.OrderLineItems)
{
DBConnection connection = DBConnection.getInstance();
connection.conn.Open();
using (SqlCeCommand query = new SqlCeCommand(OrderCommandList.cmdInsertOrderDetails, connection.conn))
{
query.Parameters.AddWithValue("@OrderID", orderForeignKey);
query.Parameters.AddWithValue("@ProductID", od.ProductID);
query.Parameters.AddWithValue("@OrderQty", od.QtyOrdered);
query.ExecuteNonQuery();
}
connection.conn.Close();
}
}
您有此問題標記爲C#,因此知道您目前使用哪些C#代碼來保存數據可能很有用。這可能會影響最佳的處理方式。 – jmcilhinney