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

时间:2015-04-20 04:38:33

标签: c# sql-server ado.net transactionscope

我试图在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内插入父和子?

1 个答案:

答案 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;
}