Entity Framework Core the default ORM that powers many many projects out there. It is great ORM and does its job great.
But some projects use more than one data access libraries. The post will be demonstrating how to use an existing DbConnection
with Entity Framework Core.
The following code was tested with:
- Dotnet Core 3.1
- Entity Framework Core 3.1.2
You could do it...
At Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>((IServiceProvider serviceProvider, DbContextOptionsBuilder options) => {
DbConnection connection = // Get your database connection here.
options.UseSqlServer(connection);
});
}
At OnConfiguring
public class MyDbContext : DbContext
{
private readonly DbConnection connection;
public MyDbContext(DbContextOptions options, DbConnection connection) : base(options)
{
this.connection = connection;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
options.UseSqlServer(connection);
}
}
var options = new DbContextOptionsBuilder<BloggingContext>()
.UseSqlServer(new SqlConnection(connectionString))
.Options;
using (var context1 = new BloggingContext(options))
{
using (var transaction = context1.Database.BeginTransaction())
{
using (var context2 = new BloggingContext(options))
{
...
}
}
}
If you hit System.InvalidOperationException: A transaction is already in progress; nested/concurrent transactions aren't supported.
while calling SaveChanges()
, try the following
ctx.Database.UseTransaction((DbTransaction)transaction); // transaction is returned when you called BeginTransaction()
As per stated in the documentation this only works for relational database only.
Top comments (0)