问题描述
我正在尝试使用带有MySQL Connector的新的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
获取连接
因为我必须在应用程序中使用 try
语句中的 connection.Open()
进行测试。如果没有有效的连接,则控制台应用程序应尝试启动MySQL Server并重试。
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
中获取c $ c>?
How can I get the Connection
from the DbContext
?
在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
()包提供了扩展方法为此-您可以使用 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
这篇关于实体框架核心:如何从DbContext获取连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!