Is there a default transaction for the SaveChanges method? - entity-framework

If I made multiple operations with the same Entity Framework DbContext (add and update)
with one call to SaveChanges, are those changes will be done as a Transaction or not?
using (MyContext context = new MyContext())
{
context.Table1.Add(entity1);
context.Table2.Add(entity2);
context.SaveChanges();
}
or is there a chance to execute just one of them without executing the other?

Yes, it's wrapped in a transaction:
In all versions of Entity Framework, whenever you execute
SaveChanges() to insert, update or delete on the database the
framework will wrap that operation in a transaction. This transaction
lasts only long enough to execute the operation and then completes.
When you execute another such operation a new transaction is started.
https://learn.microsoft.com/en-us/ef/ef6/saving/transactions
You can't do any partial save, otherwise, your DbContext could get into inconsistent state. You can only call SaveChanges multiple times after each change operation.

Related

Is EntityFrameworks AddRange Method Transactional

When I use the AddRange method from the Entity Framework and then call SaveChanges, if one of the Entities fails to be inserted into the DB, will everything be rollbacked?
I don't want to use explicit Transactions.
From msdn doc:
SaveChanges operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.
https://msdn.microsoft.com/en-us/library/bb336792(v=vs.110).aspx
I hope it helps!

DbContextTransaction Rollback

Entity Framework 6 introduced a new way to support transactions in the DbContext with the BeginTransaction method:
var db = new MyDbContext();
using(var tx = db.Database.BeginTransaction())
{
// update entities
try
{
db.SaveChanges();
tx.Commit();
}
catch(Exception)
{
tx.Rollback();
}
}
Is the Rollback() call in the method necessary? What happens if it is not called on an exception? I know when using TransactionScope it will roll back the transaction automatically when it is disposed and Complete is not called. Does DbContextTransaction behave similarly?
No it is not necessary to explicitly call Rollback. The tx variable will be disposed when the using block finishes, and the transaction will be rolled-back if Commit() has not been called.
I have tested this using SQL Server Activity Monitor, by observing the locks held on the database objects, as well as querying against the database to observe when the data is rolled back, using the nolock hint in my select statement to be able to view uncommitted changes in the database.
E.g. select top 10 * from [tablename] (nolock) order by modifiedDate
To the EF, the database provider is arbitrary and pluggable and the
provider can be replaced with MySQL or any other database that has an
EF provider implementation. Therefore, from the EF point of view,
there is no guarantee that the provider will automatically rollback
the disposed transaction, because the EF does not know about the
implementation of the database provider.
This answer pretty much explains everything and confusion with all msdn docs having that Rollback called explicitly: https://stackoverflow.com/a/28915506/5867244

Can I continue using DbContext after it has thrown an exception?

I'm aware of two different scenarios in which exceptions can be produced when working with an Entity Framework DbContext:
Enumerating a query (could throw a EntityCommandExecutionException)
Calling SaveChanges (could throw a DbUpdateException)
Within a single instance of DbContext, I'm wanting to catch these exceptions, try to recover if applicable, and then repeat the operation.
Specifically, if a call to SaveChanges throws an exception because of a deadlock, I would like to retry the call to SaveChanges. I already know how to detect this situation and perform the retry.
I saw this answer here, which indicates that an SQL connection shouldn't be used after a deadlock. This indicates that I should restart the entire DbContext and higher-level operation to recover from such exceptions.
What I'm not sure about is whether it's safe to continue using the DbContext after it has thrown an exception such as this. Will it enter an unusable state? Will it still work but not function correctly? Will SaveChanges no longer occur transactionally?
If you don't supply the DbContext with an already opened SQL connection, the DbContext will open and close the connection for you when you call SaveChanges. In that case there is no danger in keeping the DbContext around, except of course that the entities the DbContext holds on to might be in an invalid state (because this could be the reason that the SQL exception was thrown).
Here's an example of a DbContext that is suppied by an opened SQL connection and transaction:
using (var connection = new SqlConnection("my connection"))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var context = new DbContext(connection))
{
// Do useful stuff.
context.SaveChanges();
}
transaction.Commit();
}
}
If you supply the DbContext with a SqlConnection that runs in the context of a transaction, this answer holds.
Note that Entity Framework will not create a nested transaction. It simply checks whether the connection is "enlisted in user transaction". If SaveChanges already runs in a transaction, no transaction is started. Entity Framework however is unable to detect if the database has aborted the transaction because of a severe failure (such as a database deadlock). So if a first call to SaveChanges fails with something like a deadlock and you catch and recall SaveChanges, Entity Framework still thinks it is running inside a transaction.
This means that this second call is executed without a transaction and this means that when the operation fails halfway, the already executed statements will NOT be rolled back since there is no transaction to rollback.
The problem of the torn SaveChanges operation could have been prevented if Entity Framework used nested transactions, but it still wouldn't solve the general problem of consistency.
Entity Framework creates connections and transactions for us when we do not supply them explicitly. We only need/want to supply a connection and transaction explicitly when the call to SaveChanges is part of a bigger overall transaction. So even if EF created a nested transaction for us and committed this before returning from SaveChanges, we're in trouble if we call SaveChanges a second time, since this 'nested' transaction actually isn't nested at all. When EF commits this 'nested' transaction, it actually commits the only transaction there is, which means that the entire operation we needed to be atomic is torn; all changes done by SaveChanges are committed, while the operations that might came after this call didn't run. Obviously this is not a good place to be.
So moral of the story is that either you let Entity Framework handle connections and transactions for you and you can redo calls to SaveChanges without risk, or you handle transactions yourself and will have to fail fast when the database throws an exception; you shouldn't call SaveChanges again.

Should I use TransactionScope with DbContext

According to this link: EF Code First DBContext and Transactions
I should wrap the savechanges in a TransactionScope using statement.
I thought the SaveChanges works like or is a transactional method.
Example:
In a service method I am deleting and adding different entities in one http request at the end of the service method I do a SaveChanges one ONE Context.
I will have never multiple context. Its always the same context inject by Ninject created for the lifetime of a http request and shared among the repositories.
So is it true that I only need to wrap tehe DbContext.SAveChanges in a TransactionScope when I have multiple dbcontext ? - because these could be multiple databases aka a distributed transaction - ?
It is not necessary to wrap your SaveChanges call in another TransactionScope if;
If you are not trying to use multiple context in the same transaction.
If you are not making multiple SaveChanges calls even with the same context. For instance, one SaveChanges after Delete, another SaveChanges after add...
In summary, you can do multiple delete/add operations with the same context, and call the SaveChanges method once in the end - they will all be applied in one transaction. TransactionScope is only necessary if you have nested transaction scenarios.

Atomic transactions in Entity Framework 4.1 Code First without stored procedures

Is there a way to implement transactions in code first without having to write stored procedures?
I have some scenarios where multi-table entries need to be created with unique guids before a final table entry can be created. Is this something I can code using EF alone?
DbContext.SaveChanges() method uses a transaction . So it is Atomic and you don't want to use stored procedures. The unitOfWork patter is implemented in EF itself to accomplish this.
But let's say you are using two DbContext instances to d your job , then you need to wrap your work with a transaction scope like this,
using (var scpe=new TransactionScope()){
...
context1.SaveChanges();
....
context.SaveChanges();
scope.Complete();
}
SaveChanges operates within a transaction. SaveChanges will roll back
that transaction and throw an exception if any of the dirty
ObjectStateEntry objects cannot be persisted.
See the documentation