C# 在TransactionScope内插入父子项导致外键约束错误
我试图在C# 在TransactionScope内插入父子项导致外键约束错误,c#,sql-server,ado.net,transactionscope,C#,Sql Server,Ado.net,Transactionscope,我试图在TransactionScope中插入父子关系的数据,我得到了与外键约束冲突的insert语句。这是我的密码: using (var scope = new TransactionScope()) { try { discount = discountDataAccess.Insert(discount); switch (discount.Type) { case eDiscountType.Per
TransactionScope
中插入父子关系的数据,我得到了与外键约束冲突的insert语句。这是我的密码:
using (var scope = new TransactionScope())
{
try
{
discount = discountDataAccess.Insert(discount);
switch (discount.Type)
{
case eDiscountType.PerCustomer:
InsertDiscountCustomer(discount.Id, idList);
break;
case eDiscountType.PerPackage:
InsertDiscountPackage(discount.Id, idList);
break;
}
scope.Complete();
return discount;
}
catch (Exception ex)
{
scope.Dispose();
throw;
}
}
当插入DiscountCustomer
或DiscountPackage
时,Discount.Id
仍然是0
,因为在调用scope.Complete()
之前,没有数据插入数据库。因此,基本上,我无法保存折扣客户
或折扣套餐
,直到我提交折扣
,并且交易
在成功保存后才提交
有没有办法在TransactionScope
中同时插入父级和子级?我发现分布式事务不可能这样做,因为TransactionScope
仍在方法的上下文中,在调用scope.Complete()
之前不会插入任何内容,但是它可以通过SqlTransaction
类完成,该类可以从SqlConnection
中检索
try
{
var transaction = connection.BeginTransaction();
discount = discountDataAccess.Insert(discount, transaction);
switch (discount.Type)
{
case eDiscountType.PerCustomer:
InsertDiscountCustomer(discount.Id, idList, transaction);
break;
case eDiscountType.PerPackage:
InsertDiscountPackage(discount.Id, idList, transaction);
break;
}
transaction.Commit();
return discount;
}
catch (Exception ex)
{
if (transaction != null)
transaction.Rollback();
throw;
}