Entity Framework Core (EF Core) and Dapper in short words is an ORM for accessing databases in the ASP.NET Core application.

I am not going to explain how to use EF Core or Dapper. There are already many posts and tutorials out there.

This article is for those who are familiar with EF Core & Dapper and are looking to reuse the database connection context of EF Core for Dapper queries while using in a single method or transaction, to avoid re-opening a new Database connection for using dapper queries.

Reusing connection will reduce overhead in the Database and in turn improve performance. You can also set Database context pooling to improve performance.

A sample code snippet is given below.

Entity Framework Core

var users = context.Users.Where(x => x.UserTypeId == 1).FirstOrDefault();

Dapper

var data = await context.Database.GetDbConnection().ExecuteAsync("select * from users").ConfigureAwait(false);

As you can see here the same Database context connection which is dependency injected for EF Core is being reused for querying using Dapper.

context.Database.GetDbConnection() – This code will help you fetch EF Core context connection to re-use for dapper.

Last modified: November 30, 2020

Author

Comments

Write a Reply or Comment

Your email address will not be published.