Using Entity Framework to quickly test database connectivity

ado.net ado.net-entity-data-model entity-framework

Question

[I am new to ADO.NET and the Entity Framework, so forgive me if this questions seems odd.]

In my WPF application a user can switch between different databases at run time. When they do this I want to be able to do a quick check that the database is still available. What I have easily available is the ObjectContext. The test I am preforming is getting the count on the total records of a very small table and if it returns results then it passed, if I get an exception then it fails. I don't like this test, it seemed the easiest to do with the ObjectContext.

I have tried setting the connection timeout it in the connection string and on the ObjectConntext and either seem to change anything for the first scenario, while the second one is already fast so it isn't noticeable if it changes anything.

Scenario One

If the connect was down when before first access it takes about 30 seconds before it gives me the exception that the underlying provider failed.

Scenario Two

If the database was up when I started the application and I access it, and then the connect drops while using the test is quick and returns almost instantly.

I want the first scenario described to be as quick as the second one.

Please let me know how best to resolve this, and if there is a better way to test the connectivity to a DB quickly please advise.

1
5
11/9/2009 1:29:00 AM

Accepted Answer

There really is no easy or quick way to resolve this. The ConnectionTimeout value is getting ignored with the Entity Framework. The solution I used is creating a method that checks if a context is valid by passing in the location you which to validate and then it getting the count from a known very small table. If this throws an exception the context is not valid otherwise it is. Here is some sample code showing this.

public bool IsContextValid(SomeDbLocation location)
{
    bool isValid = false;

    try
    {
        context = GetContext(location);
        context.SomeSmallTable.Count();
        isValid = true;                
    }
    catch
    {
        isValid = false;
    }

    return isValid;
}
3
1/26/2010 7:56:00 PM

Popular Answer

You may need to use context.Database.Connection.Open()



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow