When you create a new EntityCollection object, the connection doesn't attempt to open the database until you try and do something with that collection. I need to determine whether or not an Entity collection has a valid connection or not, and I can't find an efficient method of doing it.
Currently I've got this in my code:
var db = new MyEntityCollection(); try { var checkworking = from c in db.Customers select c; } catch { ConnectToBackUp(); }
Which is not only horrible code, but very slow since it waits an age to determine whether or not the connection is active before throwing an exception.
I know I can control how long it waits before giving up by using ConnectionTimeout but that's just another ugly hack that makes a bad situation worse.
Surely there's a better way of doing this?
In EntityFramework Core you can simply call: Database.CanConnect ();. 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. @MarianoSoto are you sure?
EF Core comes with an in-memory database that we use for internal testing of EF Core itself. This database is in general not suitable for testing applications that use EF Core.
EF Core tests the SQL Server provider primarily by running it against a local SQL Server instance. These tests run tens of thousands of queries in a couple of minutes on a fast machine. This illustrates that using the real database system can be a performant solution.
Instead, EF Core is a common set of patterns and concepts that can be used with any database system. EF Core database providers then layer database-specific behavior and functionality over this common framework.
Simplest:
private bool TestConnection() { var db = new MyEntityCollection(); int oldTimeOut = db.CommandTimeout; try { db.CommandTimeout = 1; db.Connection.Open(); // check the database connection return true; } catch { return false; } finally { db.CommandTimeout = oldTimeOut; } }
Update for EF6:
using System.Data.Common; ... public bool TestConnection() { using (var db = new MyEntityCollection()) { DbConnection conn = db.Database.Connection; try { conn.Open(); // check the database connection return true; } catch { return false; } } }
Are you just wanting to see if the DB connection is valid. If so take a look at the objectcontext.databaseExists()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With