DEV Community

Ryan Teh Hoon Meng
Ryan Teh Hoon Meng

Posted on

3 1

Using Existing Database Connection's with Entity Framework Core

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);
    }
}

In your code

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs