Transactions in Entity Framework SQL Transactions in Entity Framework Database Applications SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Table of Contents Implicit Transactions in EF Using TransactionScope Transactional DbContext.SaveChanges() Optimistic Concurrency Control in EF: Last Wins and First Wins Strategies Using TransactionScope Using EF Explicit Transactions
Implicit Transactions in Entity Framework
Transactions in Entity Framework (EF) In EF DbContext.SaveChanges() implicitly runs in a transaction Either all changes are persisted, or none of them var context = new SoftUniEntities(); var town = new Town { Name = "Developer City " }; context.Towns.Add(town); var addr = new Address { AddressText = "5, Dev Rd.", Town = town }; context.Addresses.Add(addr); var ev = new Event { Address = addr, Name = "Party", Date = new DateTime(2015, 1, 1) }; context.Events.Add(ev); context.SaveChanges(); Implicit transaction: either town + address + event will be inserted or nothing
Transactional EF SaveChanges() Live Demo
Optimistic Concurrency Control in EF EF runs in optimistic concurrency mode (no locking) By default the conflict resolution strategy in EF is "last wins" The last change overwrites all previous concurrent changes Enabling "first wins" strategy for certain property in EF: ConcurrencyMode=Fixed (in DB first project) [ConcurrencyCheck] (in code first projects)
Last wins: the second user overwrites the first user's changes Last Wins – Example var contextFirst = new SoftUniEntities(); var lastProjectFirstUser = contextFirst.Projects .OrderByDescending(p => p.ProjectID).First(); lastProjectFirstUser.Name = "Changed by the First User"; // The second user changes the same record var contextSecondUser = new SoftUniEntities(); var lastProjectSecond = contextSecondUser.Projects lastProjectSecond.Name = "Changed by the Second User"; // Conflicting changes: last wins contextFirst.SaveChanges(); contextSecondUser.SaveChanges(); Last wins: the second user overwrites the first user's changes
First wins: the second user gets DbUpdateConcurrencyException First Wins – Example var contextFirst = new SoftUniEntities(); var lastTownFirstUser = contextFirst .Towns.OrderByDescending( t => t.TownID).First(); lastTownFirstUser.Name = "First User"; var contextSecondUser = new SoftUniEntities(); var lastTownSecondUser = contextSecondUser.Towns .OrderByDescending(t => t.TownID).First(); lastTownSecondUser.Name = "Second User"; contextFirst.SaveChanges(); contextSecondUser.SaveChanges(); First wins: the second user gets DbUpdateConcurrencyException
Optimistic Concurrency in EF Live Demo
Managing Transactions in .NET Apps TransactionScope Managing Transactions in .NET Apps
TransactionScope Class In .NET environment we can implement implicit transactions with TransactionScope Each operation in transaction scope joins the existing ambient transaction Advantages of TransactionScope Easier to implement, more efficient Supports distributed transactions (MSDTC) Disadvantages: May not be supported in cloud environment
Using TransactionScope When instantiating TransactionScope You either join the existing (ambient) transaction Or create a new ambient transaction Or you don't apply transactional logic at all The transaction coordinator (MSDTC) determines to which transaction to participate based on If there is an existing active transaction The value of the TransactionScopeOption parameter
The TransactionScope Class TransactionScopeOption specifies which transaction to be used (new / existing / none) TransactionScopeOption Transaction Already Exists? Action Required (default) No New transaction is created Yes Existing ambient transaction is used RequiresNew New transaction is explicitly created Suppress No transaction is used
TransactionScope – Example void RootMethod() { using (TransactionScope tran = new TransactionScope()) /* Perform transactional work here */ SomeMethod(); tran.Complete(); } void SomeMethod() using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required)) Create a new transaction Joins the existing transaction
Completing a TransactionScope The method Complete() informs the transaction coordinator that it is acceptable to commit the transaction If not called, the transaction will be rolled back Calling it doesn't guarantee that the transaction will be committed At the end of the using block of the root transaction, it is committed Only if the root transaction scope and all joined transaction scopes have called Complete()
TransactionScope Live Demo
Explicit Transactions in EF Using Database.BeginTransaction()
Explicit Transactions in EF var context = new SoftUniEntities(); using (var dbContextTransaction = context.Database.BeginTransaction()) { try context.Database.ExecuteSqlCommand("UPDATE Employees " + "SET Salary = Salary * 1.2 WHERE LastName = 'Wilson'"); var empsQuery = context.Employees.Where( e => e.Town.Projects.Count() >= 5); foreach (var emp in empsQuery) emp.JobTitle += "Senior " + emp.JobTitle; context.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) dbContextTransaction.Rollback();
Explicit Transactions in EF Live Demo
Transactions in Entity Framework https://softuni.bg/courses/database-applications/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Databases" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.