Entity Framework Core:如何从 DbContext 获取连接? [英] Entity Framework Core: How to get the Connection from the DbContext?

查看:40
本文介绍了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

这篇关于Entity Framework Core:如何从 DbContext 获取连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆