Reputation: 2639
I have a set of questions regarding the use of transactions in EF 6. I use the following code template for my database queries:
using (var ctx = new MyContext(connectionString))
{
using (var tx = ctx.Database.BeginTransaction(IsolationLevel.Snapshot))
{
try
{
// query database
ctx.SaveChanges();
tx.Commit();
}
catch(Exception ex)
{
tx.Rollback();
if(ex is A) // handle A
if(ex is B) // handle B
throw;
}
}
}
I will be querying the database only once and invoking SaveChanges()
only once. Is there any need to rollback the transaction if an exception occurs?
Some of my transactions will only be reading data, so I won't be invoking SaveChanges()
. In this case, should I still be calling Commit()
?
I'm thinking of using SqlAzureExecutionStrategy
for connection resiliency. At one point do transient failures occur? Is it only during the execution of the query or the invocation of SaveChanges()
? How about the initialization of ctx
, tx
, and calling of Commit()
? Can they cause such failures?
Is there a less compact way of querying the database inside of a transaction? For every single query, I need to use the above code template which significantly duplicates code such as the two using statements, try-catch block, and generic exception handling. I believe the last one can be achieved by deriving from SqlAzureExecutionStrategy
or DbExecutionStrategy
. I'm all for refactoring code as much as possible.
Upvotes: 0
Views: 1703
Reputation: 2144
You dont have to actually use transactions in Entity Framework.
The default isolation mode is read committed and fits perfectly to 99% of your needs, eg. reading data. When you want to save the changes you made to the database (Create, Update, Delete), EntityFramework is smart enough to create a transaction without your notice behind the scenes to wrap the changes. You can be sure that everything will be saved or every change will be discarded (Atomicity).
Look Here https://coderwall.com/p/jnniww
SqlAzureExecutionStrategy for connection resiliency
. But, this feature is complemented by the new ADO.Net idle connection resiliency in .NET Framework 4.5.1 http://blogs.msdn.com/b/dotnet/archive/2013/10/17/net-framework-4-5-1-rtm-gt-start-coding.aspxThe Basic Entity Framework Operations Block..
using (var context = new ProductContext())
{
try
{
// Perform data access using the context
context.SaveChanges();
}
catch(Exception ex)
{
//handle exception
}
}
Hope it may Help you, Have a nice day.
Upvotes: 1