I have product that already uses ADO.Net to access SQL Server and I'm using Entity Framework Core for some new functionality. 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.
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. This worked for me. I do CRUD operations using both ADO.NET and using EF on the same transaction.
//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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.