Using Entity Framework to quickly test database connectivity entity-framework


[Please excuse my ignorance if this inquiry appears strange; I'm new to ADO.NET and the Entity Framework.]

A user may run-time switch between many databases in my WPF application. I want to be able to verify that the database is still accessible when they do this by doing a quick check. The ObjectContext is something I can readily access. Getting the count of all the entries in a very tiny table is the test I'm running; if it produces results, it passes; if I receive an error, it fails. This test bothers me since it appeared the simplest to complete using the ObjectContext.

For the first situation, I've tried changing the connection timeout in the connection string and on the ObjectContext, but neither seems to make a difference, whilst for the second, it's already fast, so it doesn't matter whether it makes a difference.

Situation 1

It takes roughly 30 seconds for me to get the exception indicating the underlying provider failed if the connect was down when I initially accessed the site.

Scenario No. 2

If I access a database that was already running when I launched the program, but the connection dies later, the test runs quickly and returns virtually immediately.

I would want the first scenario to be just as rapid as the second.

Please let me know how to handle this issue the best manner possible, and if there is a faster approach to verify the connection to a database, please let me know.

11/9/2009 1:29:00 AM

Accepted Answer

There isn't really a simple or fast solution to this. With Entity Framework, the ConnectionTimeout value is ignored. The technique I developed verifies whether a context is legitimate by receiving the location you want to verify and then extracting the count from a known, little table. The context is valid unless this throws an exception in which case it is not. This may be seen in the following example code.

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

        context = GetContext(location);
        isValid = true;                
        isValid = false;

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

Popular Answer

Use context.Database.Connection.Open if necessary ()

Related Questions


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