Resilient Connections in Entity Framework Core
When you work with databases in your application, you may face connection issues from time to time which is beyond our control. When this happens normally the application will raise a connection timeout or server not available exception. In Entity Framework core you can overcome this kind of scenario by setting up resilient connections with exponential retries.
The code snippet given below will retry to connect up to 10 times in case of a failure with a delay of 30 seconds in-between each try.
services.AddDbContext(o => { o.UseSqlServer(connectionString, sqlServerOptionsAction: options => { options.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); });
Also, when you enable retries in EF Core connections, each operation you perform will become its own retriable operation. So that means whenever we perform a query or a call to the SaveChanges method, it will be retried as a unit during a transient failure scenario. But when you initiate a transaction block in your code using BeginTransaction, then you are defining your own group that needs to treated as a single unit.
So, in this case, you will need to manually invoke an execution strategy with a delegate method that contains all that
var strategy = blogContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async () => { using (var transaction = blogContext.Database.BeginTransaction()) { blogContext.PostItems.Update(postItem); await blogContext.SaveChangesAsync(); if (raisePostChangedEvent) await eventLogService.SaveEventAsync(postChangedEvent); transaction.Commit(); }
No Comments
Adding Serilog to Azure Functions created using .NET 5
Posted 4/3/2021Learn how to split log data into different tables using Serilog in ASP.NET Core
Posted 4/23/2020Writing logs to different files using Serilog in ASP.NET Core Web Application
Posted 4/15/2020Write your logs into database in an ASP.NET Core application using Serilog
Posted 2/2/2020Rollover log files automatically in an ASP.NET Core Web Application using Serilog
Posted 1/19/2020