Skip to main content
 首页 » 编程设计

c#之确保插入发生在多个表上

2024年02月05日14zdz8207

我在 SqlServer 中有两个表“EnrolledSubjects”和“StudentAccounts”。显然,录取的科目应该归前者,学费应该归后者。我对两个表都使用了简单的 Insert 语句,但问题是,当其中一个表插入失败时,另一个表不能插入任何内容。我可以像这样使用 try-catch:

try 
{ 
  insert statement to EnrolledSubjects table; 
  insert statement to StudentAccounts table; 
} catch(Exception ex) { 
  get the error here 
} 

但是如果插入EnrolledSubjects没有错误,但是插入StudentAccounts时出现错误怎么办?那么这意味着我需要删除插入到 EnrolledSubjects 表中的任何内容。
你能告诉我如何根据我的规范实现这个权利吗?谢谢你。

请您参考如下方法:

正如@TimBiegeleisen 在评论中提到的,您将需要一个 TransactionScope :

try 
{ 
    using (var scope = new TransactionScope()) 
    { 
        // insert statement to EnrolledSubjects table; 
        // insert statement to StudentAccounts table; 
        scope.Complete(); // don't forget this! 
    } 
} 
catch(Exception ex) 
{ 
    // get error here 
} 

如果 scope.Complete() 没有被调用,事务将回滚。如果您的项目还没有,您将需要添加对 System.Transactions 的引用。