完整错误:.Net SqlClient数据提供程序INSERT语句与FOREIGN KEY约束“ FK_SalesOrder_SalesOrderHead”冲突。在数据库“ ControlSecurity”的表“ dbo.SalesOrderHead”的列“ id”中发生了冲突。
数据库表信息: FK_SalesOrder_SalesOrderHead(关系)具有来自SalesOrderHead的主键ID,并且FK = SalesOrderID。
SalesOrderInsert(Stored Procedure)
[dbo].[SalesOrderInsert]
@SalesOrder udtSalesOrder readonly
AS
BEGIN
INSERT INTO SalesOrder
(ProductID,Quantity,UnitPrice,SalesOrderID)
SELECT ProductID,Quantity,UnitPrice,SalesOrderID
FROM @SalesOrder
END
用户定义表udtSalesOrder:
CREATE TYPE [dbo].[udtSalesOrder] AS TABLE(
[ProductID] [int] NULL,
[Quantity] [int] NULL,
[SalesOrderID] [int] NULL,
[UnitPrice] [int] NULL
)
我要向SalesOrderHead
表中添加一行,然后获取作用域ID,并使用存储过程将数据表中的多行插入SalesOrder
表中。所有这些都在C#代码的一次事务中完成。但是似乎第二个ExecuteNonQuery不知道它是事务的一部分,或者我对事务范围的理解不正确。我应该在这里发布对存储过程的查询。我不确定。
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbconn"].ToString()))
{
try
{
con.Open();
using (var tran = con.BeginTransaction())
{
try
{
SqlCommand cmd = new SqlCommand("Insert into SalesOrderHead(cust_id,Description,OrderDate,DeliveryDate,Priority,CustomerRef) VALUES(@cust_id,@Description,@OrderDate,@DeliveryDate,@Priority,@CustomerRef) SELECT @id = CAST(SCOPE_IDENTITY() AS int)",con,tran);
cmd.Parameters.AddWithValue("@cust_id", CustomersList.EditValue);
cmd.Parameters.AddWithValue("@Description", Remarks.Text);
cmd.Parameters.AddWithValue("@OrderDate", OrderDate.DateTime);
cmd.Parameters.AddWithValue("@DeliveryDate", DeliveryDate.DateTime);
cmd.Parameters.AddWithValue("@Priority", PriorityComboBox.Text);
cmd.Parameters.AddWithValue("@CustomerRef", CustomerRef.Text);
cmd.Parameters.AddWithValue("@id", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
var SalesOrderHeadID = cmd.Parameters["@id"].Value;
cmd.Parameters.Clear();
cmd.CommandText = "SalesOrderInsert";
//cmd = new SqlCommand("SalesOrderInsert", con, tran);
//cmd.Transaction = tran;
cmd.CommandType = CommandType.StoredProcedure;
//Add from SalesOrderTB to SalesOrder stored procedure
cmd.Parameters.AddWithValue("@SalesOrder", SalesOrderTB);
cmd.ExecuteNonQuery();
// Record inserted in both table
tran.Commit();
XtraMessageBox.Show("Added to database success");
con.Close();
}
catch (SqlException ex)
{
tran.Rollback();
Console.WriteLine(ex.Source + ex.Message);
}
}
}
catch (Exception)
{
throw;
}
}