[英]How to create a DBContext as part of an existing transaction in Entity Framework Core
I have product that already uses ADO.Net to access SQL Server and I'm using Entity Framework Core for some new functionality. 我有已经使用ADO.Net来访问SQL Server的产品,并且我正在使用Entity Framework Core来提供一些新功能。 The problem I'm having is I have some operations that must be done in a single transaction and the first few actions are implemented through ADO.Net and I need add an extra action using Entity Framework so I need to pass the transaction to the DBContext. 我遇到的问题是我必须在单个事务中完成一些操作,并且前几个动作是通过ADO.Net实现的,我需要使用实体框架添加一个额外的动作,因此我需要将事务传递给DBContext 。
When I need to use an existing connection I can do: 当我需要使用现有连接时,可以执行以下操作:
var dbc = new MyDBContext(optionsBuilder.UseSqlServer(connection).Options)
Is there something similar where I pass in a transaction instead of a connection? 我在事务而不是连接中传递类似的内容吗? Should I be doing this in a completely different way? 我应该以完全不同的方式来执行此操作吗?
You can do something like this to create DbContext with your existing SqlTransaction. 您可以执行类似的操作以使用现有的SqlTransaction创建DbContext。 This worked for me. 这对我有用。 I do CRUD operations using both ADO.NET and using EF on the same transaction. 我在同一事务上同时使用ADO.NET和EF进行CRUD操作。
//create connection and transaction do usual ADO.NET stuff
SqlTransaction transaction = ... // existing transaction
var existingConnection = transaction.Connection;
var contextOwnsConnection = false;
using (var db = new MyDbContext(existingConnection, contextOwnsConnection))
{
db.Database.UseTransaction(transaction);
//do something with db
}
// optionally do usual ADO.NET stuff ....
transaction.Commit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.