Why you shouldn't use Entity Framework with Transactions
Links
EntityFramework
This is a .net ORM Mapper Framework from Microsoft to help you talking with your Database in an object oriented manner. Wikipedia
Database Transaction
A database transaction, by definition, must be atomic, consistent, isolated and durable. Database practitioners often refer to these properties of database transactions using the acronym ACID. Transactions in a database environment have two main purposes:
- To provide reliable units of work that allow correct recovery from failures and keep a database consistent even in cases of system failure, when execution stops (completely or partially) and many operations upon a database remain uncompleted, with unclear status.
- To provide isolation between programs accessing a database concurrently. If this isolation is not provided, the program's outcome are possibly erroneous. Wikipedia
.NET Transactions
A .NET Transaction can be used in different ways by different frameworks to support transactions. The .NET Transaction itself is not connected with the database by any means. MSDN
.NET Transactions and the EntityFramework
If you are using the Entity Framework during an opened TransactionScope, EntityFramework will open a new Transaction right with the next command that will be sent to the Database (CRUD Operation).
Consider this code block:
using (var transaction = new System.Transactions.TransactionScope())
{
// DBC = Database Command
// create the database context
var database = new DatabaseContext();
// search for the user with id #1
// DBC: BEGIN TRANSACTION
// DBC: select * from [User] where Id = 1
var userA = database.Users.Find(1);
// DBC: select * from [User] where Id = 2
var userB = database.Users.Find(2);
userA.Name = "Admin";
// DBC: update User set Name = "Admin" where Id = 1
database.SaveChanges();
userB.Age = 28;
// DBC: update User set Age = 28 where Id = 2
database.SaveChanges();
// DBC: COMMIT TRANSACTION
transaction.Complete();
}
https://gist.github.com/SeriousM/e6b30db2b21e7e602655#file-bad_example-cs
The database.SaveChanges() call sends your changes to the database and executes them but they are not really persisted because you are in the database transaction scope. transaction.Complete() actually finishes the database transaction and your data is saved.
That behavior is actually cool and very useful, right?
NO. Absolutely not. full stop.
Why not using .NET Transactions along with EntityFramework
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).
By using transactions in EntityFramework, you change that behavior and force everyCRUD operation during a transaction scope to be executed in serializable isolation mode which is the highest and most blocking type. No process will be able to access the tables you have touched (even reading from it) during your transaction. That can lead to Deadlocks pretty fast and you want to avoid them at all costs!
That's how the code looks like without the explicit usage of transactions:
// DBC = Database Command
// create the database context
var database = new DatabaseContext();
// search for the user with id #1
// DBC: select * from [User] where Id = 1
var userA = database.Users.Find(1);
// DBC: select * from [User] where Id = 2
var userB = database.Users.Find(2);
userA.Name = "Admin";
userB.Age = 28;
// DBC: BEGIN TRANSACTION
// DBC: update User set Name = "Admin" where Id = 1
// DBC: update User set Age = 28 where Id = 2
// DBC: COMMIT TRANSACTION
database.SaveChanges();
https://gist.github.com/SeriousM/e6b30db2b21e7e602655#file-good_example-cs
Rule of Thumb: Save only once per task and don't use transactions.
Edit: thanks to @seimur - One thread should have access to one instance of DbContext which works best in web applications where every request acts as one thread. In windows applications every command or task should have one DbContext which is not shared. If you share the DbContext between threads you might run into issues like having reads sneaked into a foreign transaction.
Why you shouldn't use Entity Framework with Transactions的更多相关文章
- (转载)Why you shouldn't use Entity Framework with Transactions
Why you shouldn't use Entity Framework with Transactions EntityFramework This is a .net ORM Mapper F ...
- Entity Framework - Using Transactions or SaveChanges(false) and AcceptAllChanges()?
LINK With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transact ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- Entity Framework Core 1.1 升级通告
原文地址:https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-entity-framework-core-1-1/ 翻译:杨晓东 ...
- Entity Framework Core 实现MySQL 的TimeStamp/RowVersion 并发控制
将通用的序列号生成器库 从SQL Server迁移到Mysql 遇到的一个问题,就是TimeStamp/RowVersion并发控制类型在非Microsoft SQL Server数据库中的实现.SQ ...
- 采用MiniProfiler监控EF与.NET MVC项目(Entity Framework 延伸系列1)
前言 Entity Framework 延伸系列目录 今天来说说EF与MVC项目的性能检测和监控 首先,先介绍一下今天我们使用的工具吧. MiniProfiler~ 这个东西的介绍如下: MVC Mi ...
- 来,给Entity Framework热热身
先来看一下Entity Framework缓慢的初始化速度给我们更新程序带来的一种痛苦. 我们手动更新程序时通常的操作步骤如下: 1)把Web服务器从负载均衡中摘下来 2)更新程序 3)预热(发出一个 ...
- 采用EntityFramework.Extended 对EF进行扩展(Entity Framework 延伸系列2)
前言 Entity Framework 延伸系列目录 今天我们来讲讲EntityFramework.Extended 首先科普一下这个EntityFramework.Extended是什么,如下: 这 ...
- Entity Framework教程(第二版)
源起 很多年前刚毕业那阵写过一篇关于Entity Framework的文章,没发首页却得到100+的推荐.可能是当时Entity Framework刚刚发布介绍EF的文章比较少.一晃这么多年过去了,E ...
随机推荐
- HTTP 405 错误 – 方法不被允许 (Method not allowed)
HTTP 协议定义一些方法,以指明为获取客户端(如您的浏览器或我们的 CheckUpDown 机器人)所指定的具体网址资源而需要在 Web 服务器上执行的动作.则这些方法如下: 介绍 OPTIONS( ...
- Android 高清加载巨图方案, 拒绝压缩图片
源地址:http://blog.csdn.net/lmj623565791/article/details/49300989 一.概述 距离上一篇博客有段时间没更新了,主要是最近有些私事导致的,那么就 ...
- 控件 UI: StateTrigger
VisualState 之 StateTrigger 示例1.自定义 StateTriggerControls/UI/VisualState/MyDeviceFamilyStateTrigger.cs ...
- shell 题
(1)有一推主机地址:a.baidu.com.....z.baidu.com如何从这些数据中提取出.baidu.com之前的字母,如:a b...z? #cat f1.txt | while read ...
- Hp自学整理html
a:hover {text-decoration:underline; color:#00FF00;}/* 鼠标悬浮在链接上时.出现下划线颜色变绿色 */ display:inline.block.i ...
- 【bzoj1497】 NOI2006—最大获利
http://www.lydsy.com/JudgeOnline/problem.php?id=1497 (题目链接) 题意 给出一个图,每一个点有一个负点权,每一条边有一个边权.选择某一条边的前提是 ...
- bzoj3283: 运算器
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...
- Win10中解决SYSTEM权限获取,删Windows old
一.[Windows.old]文件夹[右键]->[属性] 二.[安全]->[高级] 三.[更改] 四.添加[Everyone],点击[确定] 五.如下图,勾选两个选项,再[确定] 六.一路 ...
- nginx ssl证书安装配置
原理图: - 客户端生成一个随机数 random-client,传到服务器端(Say Hello) - 服务器端生成一个随机数 random-server,和着公钥,一起回馈给客户端(I got it ...
- CentOS普通用户添加sudo权限
1. 进入超级用户模式 su root 2. 添加sudoers文件写权限. chmod u+w /etc/sudoers 3.添加username到sudoers文件里(参考"root A ...