我试图在TransactionScope
内插入父子关系的数据,但我得到INSERT statement conflicted with the FOREIGN KEY constraint
错误。这是我的代码:
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()
之前没有数据插入数据库。所以基本上我无法保存DiscountCustomer
或DiscountPackage
,直到我提交Discount
并且Transaction
在两次保存成功之前都没有提交。
有没有办法在TransactionScope
内插入父和子?
答案 0 :(得分:2)
我发现分布式事务是不可能的,因为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;
}