C#/ SQL:在一个事务中执行多个插入/更新

Eli*_*eth 3 c# sql transactions insert

我有一个拥有10个属性的客户实体.

  • 其中7个属性保存在customer表中.
  • 其中3个属性保存在测试表中.

测试表中的3个属性是CustomerId,Label,Text.

当我查询这3个属性时,我得到3个这样的数据集:

CustomerId | Label  | Text
1005       | blubb  | What a day
1006       | hello  | Sun is shining
0007       |        |
Run Code Online (Sandbox Code Playgroud)

当我保存它们时,我必须在测试台上调用我的存储过程3次

在我的SP中,我检查具有特定customerId AND Label的数据集是否已经存在,然后我执行UPDATE,否则执行INSERT.

如何使用所有CommandText,CommandType,ExecuteNonQuery等东西调用存储过程3次?

Ste*_*e B 8

最简单的方法:使用TransactionScope类.

只需将调用放入一个块,如:

using(TransactionScope ts = new TransactionScope()){

    using(SqlConnection conn = new SqlConnection(myconnstring)
    {
        conn.Open();
... do the call to sproc

        ts.Complete();
        conn.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

[编辑]我还添加了SqlConnection,因为我非常喜欢这种模式.using关键字确保关闭连接,如果发生错误则传输回滚