TransactionScope 内的父子插入导致外键约束错误

Parent-Child Insertion inside TransactionScope cause foreign key constraint error

我试图在 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;
    }
} 

DiscountCustomerDiscountPackage 将被插入时,Discount.Id 仍然是 0,因为直到调用 scope.Complete() 才将数据插入数据库。所以基本上我无法保存 DiscountCustomerDiscountPackage 直到我提交 Discount 并且 Transaction 直到都成功保存才提交。

有什么方法可以在 TransactionScope 中同时插入父项和子项吗?

我发现分布式事务是不可能的,因为 TransactionScope 仍然在方法的上下文中,并且在调用 scope.Complete() 之前不会插入任何内容,但是可以通过 SqlTransaction class 可以从 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;
}