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 the DbContext
because I have to test for it at application starting using a connection.Open()
inside a try
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 the DbContext
?
Before EF6 by context.Connection
. After EF6 by context.Database.Connection
.
It seems the latest has been removed too from EFCore.
The providerName setting is not required on EF Core connection strings stored in App. config because the database provider is configured via code. You can then read the connection string using the ConfigurationManager API in your context's OnConfiguring method. You may need to add a reference to the System.
As per Microsoft “A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns.” In simplified way we can say that DbContext is the bridge between Entity Framework and Database.
DbContext is a combination of the Unit Of Work and Repository patterns. DbContext in EF Core allows us to perform following tasks: Manage database connection. Configure model & relationship. Querying database.
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
You can do the following :
using (SqlCommand cmd = (SqlCommand)database.GetDbConnection().CreateCommand())
if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With