【问题标题】:Create Transaction with context and sql command, C#使用上下文和 sql 命令创建事务,C#
【发布时间】:2017-10-19 20:56:25
【问题描述】:

我想创建一个包含两个保存的事务:一个通过实体框架的上下文,另一个使用 sql 命令。

我如何获得一个连接,将其传递给另一个并创建一个事务?

例如:

var ctx = ApplicationContext();
var tr = ctx.Transaction.where(x=>x.id=1);
tr.status = 5;
ctx.SaveChanges();

using (SqlConnection connection = new SqlConnection(ConnectionString))
 {
   using (SqlCommand command = new SqlCommand(query, connection))
   { //set query and params
     connection.Open();
     command.ExecuteNonQuery();

    }

【问题讨论】:

  • 您在这里使用的是什么版本的 EntityFramework?
  • 实体框架6

标签: c# entity-framework transactions


【解决方案1】:

我目前无法测试,但您可以查看 DbContext 的Database property。在这里,您可以找到获取事务对象和连接本身的属性和方法。

您可以将它们用于您的命令

var ctx = ApplicationContext();
using(var tr = ctx.Database.BeginTransaction())
{
    ctx.SaveChanges();

    // Not sure if at this point the connection is still open
    // or not disposed. You need to experiment here.

    using (SqlCommand command = new SqlCommand(query, ctx.Database.Connection))
    {
         command.ExecuteNonQuery();
         tr.Commit();
    }
}

但此时您会注意到存在一个名为ExecuteSqlCommand 的方法,它可能可以再次简化代码

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2017-08-16
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
相关资源
最近更新 更多