EF6 introduces the functionality of an elastic connection, which is the ability to retry a failed database operation. In some complex scenarios, it may be necessary to enable or disable the policy of retry execution, but the EF framework has not yet provided a direct set-up switch that may be added to this configuration in the future. Fortunately, it's easy to implement the setup feature yourself.
The simplest way to register an execution policy is through a code-based configuration. The following code is a typical configuration class that enables the Sqlazureexecutionstrategy policy (which allows retries to execute a known retry exception in SQL Azure).
1 usingSystem.Data.Entity;2 usingSystem.Data.Entity.SqlServer;3 4 namespaceDemo5 {6 Public classmyconfiguration:dbconfiguration7 {8 Publicmyconfiguration ()9 {Ten This. Setexecutionstrategy ("System.Data.SqlClient", () =Newsqlazureexecutionstrategy ()); One } A } -}Allow execution policy to be suspended
After the new execution policy is set, all actions follow the new execution policy. We can implement a flag parameter to switch between the default (no retry) and Sqlazureexecutionstrategy.
Note: We get or set this flag through CallContext, which ensures that our operation is correct in the asynchronous query and save in EF6.
1 usingSystem.Data.Entity;2 usingSystem.Data.Entity.Infrastructure;3 usingSystem.Data.Entity.SqlServer;4 usingSystem.Runtime.Remoting.Messaging;5 6 namespaceDemo7 {8 Public classmyconfiguration:dbconfiguration9 {Ten Publicmyconfiguration () One { A This. Setexecutionstrategy ("System.Data.SqlClient", () =Suspendexecutionstrategy -? (Idbexecutionstrategy)Newdefaultexecutionstrategy () -:Newsqlazureexecutionstrategy ()); the } - - Public Static BOOLSuspendexecutionstrategy - { + Get - { + return(BOOL?) Callcontext.logicalgetdata ("Suspendexecutionstrategy") ??false; A } at Set - { -Callcontext.logicalsetdata ("Suspendexecutionstrategy", value); - } - } - } in}Use the logo above
You can now use this flag to disable the retry execution policy on some operations.
1 using(vardb =NewBloggingcontext ())2 {3Myconfiguration.suspendexecutionstrategy =true;4 5 //Perform without retry logic6Db. Blogs.add (NewBlog {URL ="romiller.com" });7 db. SaveChanges ();8 9Myconfiguration.suspendexecutionstrategy =false;Ten One}When to use this feature
The most common scenario is that some operations we do not need to retry execution, such as user initialization transactions.
Entity Framework 6 paused retry execution policy