Entity Framework Core:如何从 DbContext 获取连接?
我正在尝试使用 MySQL 连接器的新 Entity Framework Core.
I am trying the new Entity Framework Core with MySQL Connector.
我可以获得一个有效的 DbContext
并写入数据库,这样一切都已正确设置.
I can get a valid DbContext
and write into the database so everything has been setup correctly.
我需要从 DbContext
获取 Connection
因为我必须在应用程序开始时使用 connection.Open()
测试它在 try
语句中.如果没有有效连接,控制台应用程序应尝试启动 MySQL 服务器并重试.
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.
如何从 DbContext
获取Connection
?
在 EF6 之前通过 context.Connection
.在 EF6 之后通过 context.Database.Connection
.
Before EF6 by context.Connection
. After EF6 by context.Database.Connection
.
似乎最新的也已从 EFCore 中删除.
It seems the latest has been removed too from EFCore.
Microsoft.EntityFrameworkCore.Relational
(https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Relational/) 包为此提供了扩展方法 - 您可以使用 dbContext.Database.OpenConnection()
或 dbContext.Database.GetDbConnection()
以获取 DbConnection
对象.
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.
注意:如果您安装了Microsoft.EntityFrameworkCore.SqlServer
,那么您不必显式安装此包
Note: if you have Microsoft.EntityFrameworkCore.SqlServer
installed then you don't have to explicitly install this package