Willem
Willem

Reputation: 9496

How would i reconnect Entity Frameworks connection to the DB when the connection is lost

I am working on a MVVM project using Entity Framework 5.0.

I connect to a hosted DB and sometimes Entity Framework looses connection to the DB.

What would be the best way to reconnect the connection to the DB when the connection was lost?

Upvotes: 4

Views: 2944

Answers (3)

mr. Jaylin
mr. Jaylin

Reputation: 36

I'll just leave it here in case someone, like me, is looking for an answer to this question.

Add options => options.EnableRetryOnFailure() to the OnConfiguring configuration:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=EFMiscellanous.ConnectionResiliency;Trusted_Connection=True",
            options => options.EnableRetryOnFailure());
}

Read more this.

Upvotes: 2

m4ngl3r
m4ngl3r

Reputation: 560

When connection is broken during saving your changes you simply get exception. Whole saving is done in transaction which is not committed due to the exception and EF doesn't mark its current changes set as completed. You can simply try to save changes again when that specific exception happens - EF will try to open a new connection and execute the same transaction


for ex.: well, maybe something like this:

public virtual void SubmitChanges()
{
    if (DataContext != null)
    {               
        try
        {
             DataContext.SubmitChanges();
        }
        catch (Exception whenILostMyConnection)
        {
             SubmitChanges(); //recall the sumbitChanges
        }
    }             
}

Upvotes: 1

Denis Agarev
Denis Agarev

Reputation: 1529

You can see answer in Windows Azure source code. It's common for Azure CRUD operations to put them into loops which retries to do the same operation for several times cause for some specific exceptions. But you must be very carefully with exceptions you what handle for retries cause in most cases it can make you app slower.

Upvotes: -1

Related Questions