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 AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay