我想创建一个两个保存的事务:一个通过实体框架的上下文,另一个使用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();
}
答案 0 :(得分:0)
我目前无法测试它,但你可以看一下
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的方法,可能会再次简化代码