Entity Framework Core: How to get the Connection from the DbContext?
Solution 1
The Microsoft.EntityFrameworkCore.Relational
(https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Relational/) package provides extension methods for this - you can use dbContext.Database.OpenConnection()
or dbContext.Database.GetDbConnection()
to get the DbConnection
object.
Note: if you have Microsoft.EntityFrameworkCore.SqlServer
installed then you don't have to explicitly install this package
Solution 2
You can do the following :
- If you are using System.Data.SqlClient change it to Microsoft.Data.SqlCLient since the later library will accept excplicit casting from the object of the DBContext in both EntityFramework and EntityFrameWorkCore.
- Create a command from the DBContext connection and Cast it to your SQLCommand by
using (SqlCommand cmd = (SqlCommand)database.GetDbConnection().CreateCommand())
- Check the connection state and open it if necessary.
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
- If there is a transaction in the DBContext add it to the command.
if (database.CurrentTransaction != null)
{
cmd.Transaction = database.CurrentTransaction.GetDbTransaction();
}
By doing this you will avoid any problems can appear when using comands outside the context.
nico9T
Updated on July 17, 2021Comments
-
nico9T almost 3 years
I am trying the new Entity Framework Core with MySQL Connector.
I can get a valid
DbContext
and write into the database so everything has been setup correctly.I need to get the
Connection
from theDbContext
because I have to test for it at application starting using aconnection.Open()
inside atry
statement. If there is not a valid connection, the console app should try to start MySQL Server and retry.How can I get the
Connection
from theDbContext
?Before EF6 by
context.Connection
. After EF6 bycontext.Database.Connection
.It seems the latest has been removed too from EFCore.