I am trying to configure fault tolerance settings for EF6.02. I have an application that writes a record to a database in one place of execution. The application does not depend on the SQL server, therefore, if the server does not respond, I want the application to refuse the INSERT request (via SaveChanges of DbContext) and immediately execute it.
Using the default settings, the debug log displays ten
"The first exception of type" System.Data.SqlClient.SqlException "has appeared in System.Data.dll
After ten attempts, it throws an exception, and my code continues. But I want only one attempt and, for example, the timeout for the command s s. According to the MSDN documentation, the default failover method for SQL Server is:
DefaultSqlExecutionStrategy : This is the default execution strategy. This strategy does not retry, but it will tolerate any exceptions that may be temporary to inform users that they might want to enable fault tolerance.
As mentioned in the documentation, this strategy does not repeat at all. But still I have ten attempts. I tried to create a class that inherits DbConfiguration, but I did not find any documentation on how to change this.
Can someone help me reduce the number of attempts?
UPDATE: Below is the code based on the suggestions
using System;
using System.Data.Entity;
using System.Data.Entity.SqlServer;
using System.Data.Entity.Infrastructure;
using System.Runtime.Remoting.Messaging;
namespace MyDbLayer
{
public class MyConfiguration : DbConfiguration
{
public MyConfiguration ()
{
this.SetExecutionStrategy("System.Data.SqlClient", () => SuspendExecutionStrategy
? (IDbExecutionStrategy)new DefaultExecutionStrategy()
: new SqlAzureExecutionStrategy());
}
public static bool SuspendExecutionStrategy
{
get
{
return (bool?)CallContext.LogicalGetData("SuspendExecutionStrategy") ?? false;
}
set
{
CallContext.LogicalSetData("SuspendExecutionStrategy", value);
}
}
}
}
And writing code in SQL
try
{
using (MyEntities context = new MyEntities ())
{
Log logEntry = new Log();
logEntry.TS = DateTime.Now;
MyConfiguration.SuspendExecutionStrategy = true;
context.Log.Add(logEntry);
context.SaveChanges();
}
}
catch (Exception ex)
{
logger.Warn("Connection error with database server.", ex);
}
finally
{
MyConfiguration.SuspendExecutionStrategy = false;
}