Entity Framework Core: How to get the Connection from the DbContext?

試著忘記壹切 提交于 2019-12-03 08:27:43

问题


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.


回答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



来源:https://stackoverflow.com/questions/41935752/entity-framework-core-how-to-get-the-connection-from-the-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!