Download presentation
Presentation is loading. Please wait.
1
Transactions in Entity Framework
SQL Transactions in Entity Framework Database Applications SoftUni Team Technical Trainers Software University © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
2
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
3
Implicit Transactions in Entity Framework
4
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
5
Transactional EF SaveChanges()
Live Demo
6
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)
7
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
8
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
9
Optimistic Concurrency in EF
Live Demo
10
Managing Transactions in .NET Apps
TransactionScope Managing Transactions in .NET Apps
11
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
12
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
13
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
14
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
15
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()
16
TransactionScope Live Demo
17
Explicit Transactions in EF
Using Database.BeginTransaction()
18
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();
19
Explicit Transactions in EF
Live Demo
20
Transactions in Entity Framework
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
21
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 – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
22
Free Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.