我有一个通过实体框架连接到MySQL数据库的应用程序。它100%完美地工作,但我想添加一小段代码,将测试连接到数据库的应用程序启动。
我的想法是只需对数据库运行一个小命令并捕获任何异常,但是如果出现问题(例如,App.Config丢失或数据库服务器关闭),应用程序将花费大量时间运行此代码,然后抛出异常(~1分钟)。我想这是由于连接超时等原因,但我已经摆弄了这些属性,但都无济于事。
有没有人能帮我想出去哪里的主意?
mnemlml81#
Are you just wanting to see if the DB connection is valid? If so take a look at the
using (DatabaseContext dbContext = new DatabaseContext()) { dbContext.Database.Exists(); }
http://msdn.microsoft.com/en-us/library/gg696617(v=vs.103).aspx
and for checking if a server machine is up, DB server or web services server , try this:
public PingReply Send( string hostNameOrAddress )
http://msdn.microsoft.com/en-us/library/7hzczzed.aspx
kx5bkwkv2#
The solution as @Danilo Breda pointed out is to call the DbContext.Database.Connection.Open()
It is tested with EF6.
My implementaion:
public static bool CheckConnection() { try { MyContext.Database.Connection.Open(); MyContext.Database.Connection.Close(); } catch(SqlException) { return false; } return true; }
chhqkbe13#
In EntityFramework Core you can simply call: Database.CanConnect();.
Database.CanConnect();
(using EF Core 2.2.1)
Summary: Determines whether or not the database is available and can be connected to.
Note that being able to connect to the database does not mean that it is up-to-date with regard to schema creation, etc.
nbewdwxp4#
我在我的项目中使用以下代码:
private bool TestConnectionEF() { using (var db = new SistemaContext()) { db.Database.Connection.Open(); if (db.Database.Connection.State == ConnectionState.Open) { Console.WriteLine(@"INFO: ConnectionString: " + db.Database.Connection.ConnectionString + "n DataBase: " + db.Database.Connection.Database + "n DataSource: " + db.Database.Connection.DataSource + "n ServerVersion: " + db.Database.Connection.ServerVersion + "n TimeOut: " + db.Database.Connection.ConnectionTimeout); db.Database.Connection.Close(); return true; } return false; } }
x6h2sr285#
我知道这是一个老生常谈的问题,但对于任何正在寻找新实现的人来说,这是我的答案。
我能够使用CanConnect检查数据库的状态:
CanConnect
_database.Database.CanConnect(); # Async too await _database.Database.CanConnectAsync(_cancellationTokenSource.Token);
我希望这也能帮助其他人。干杯!
kxxlusnw6#
I used the answer from @Sandor and did an extension method to use with EntityFramework Core.
Here's the code:
using Microsoft.EntityFrameworkCore; using System.Data.Common; namespace TerminalInventory { public static class ExtensionMethods { public static bool TestConnection(this DbContext context) { DbConnection conn = context.Database.GetDbConnection(); try { conn.Open(); // Check the database connection return true; } catch { return false; } } } }
Now you just have to call:
if (!context.TestConnection()) { logger.LogInformation("No database connection. Check the connection string in settings.json. {0}", configuration["connectionString"]); return; }
goqiplq27#
I am using the following code for MS SQL connection. Maybe, it will be useful for MySQL too. You don’t even need to use an EF or EF Core.
public bool IsDbConnectionOK() { SqlConnectionStringBuilder conStr = new SqlConnectionStringBuilder { DataSource = ButtonServerName.Text, // <-- My Form Elements InitialCatalog = ButtonDBName.Text, // <-- My Form Elements UserID = EditUserName.Text, // <-- My Form Elements Password = EditPassword.Text, // <-- My Form Elements IntegratedSecurity = false, ConnectTimeout = 30 }; string connectionstring = conStr.ToString(); try { using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionstring)) { connection.Open(); return true; } } catch (System.Data.SqlClient.SqlException ex) { MessageBox.Show(ex.Message + Environment.NewLine + "Error line: " + ex.LineNumber + Environment.NewLine + "Procedure name: " + ex.Procedure); return false; } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } }
7条答案
按热度按时间mnemlml81#
Are you just wanting to see if the DB connection is valid? If so take a look at the
http://msdn.microsoft.com/en-us/library/gg696617(v=vs.103).aspx
and for checking if a server machine is up, DB server or web services server , try this:
public PingReply Send( string hostNameOrAddress )
http://msdn.microsoft.com/en-us/library/7hzczzed.aspx
kx5bkwkv2#
The solution as @Danilo Breda pointed out is to call the DbContext.Database.Connection.Open()
It is tested with EF6.
My implementaion:
chhqkbe13#
In EntityFramework Core you can simply call:
Database.CanConnect();
.(using EF Core 2.2.1)
Summary: Determines whether or not the database is available and can be connected to.
Note that being able to connect to the database does not mean that it is up-to-date with regard to schema creation, etc.
nbewdwxp4#
我在我的项目中使用以下代码:
x6h2sr285#
我知道这是一个老生常谈的问题,但对于任何正在寻找新实现的人来说,这是我的答案。
我能够使用
CanConnect
检查数据库的状态:我希望这也能帮助其他人。干杯!
kxxlusnw6#
I used the answer from @Sandor and did an extension method to use with EntityFramework Core.
Here's the code:
Now you just have to call:
goqiplq27#
I am using the following code for MS SQL connection. Maybe, it will be useful for MySQL too. You don’t even need to use an EF or EF Core.