(转载)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 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 every CRUD 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.
Written by Bernhard Millauer
(转载)Why you shouldn't use Entity Framework with Transactions的更多相关文章
- 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 yo ...
- 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 ...
- 【极力分享】[C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例【转载自https://segmentfault.com/a/1190000004152660】
[C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例 本文我们来学习一下在Entity Framework中使用Cont ...
- 转载:学习Entity Framework 中的Code First
看完觉得不错,适合作为学习资料,就转载过来了 原文链接:http://www.cnblogs.com/Wayou/archive/2012/09/20/EF_CodeFirst.html 这是上周就写 ...
- 让Entity Framework支持MySql数据库(转载)
转载地址:http://www.cnblogs.com/wintersun/archive/2010/12/12/1903861.html Entity Framework 4.0 也可以支持大名鼎鼎 ...
- 转载 8天掌握EF的Code First开发之Entity Framework介绍
转载原地址: http://www.cnblogs.com/farb/p/IntroductionToEF.html Entity Framework概要 Entity Framework是微软的O ...
- 转载Entity Framework 5.0(EF first)中的添加,删除,修改,查询,状态跟踪操作
转载原出处:http://www.cnblogs.com/kenshincui/p/3345586.html Entity Framework将概念模型中定义的实体和关系映射到数据源,利用实体框架可以 ...
- 转载Entity Framework全面教程
转载原地址:http://www.cnblogs.com/lsxqw2004/archive/2009/05/31/1495240.html#_Toc228672754 预备知识 2 LINQ技 ...
- 转载Entity Framework 4.1 DbContext使用记之三——如何玩转实体的属性值?
Entity Framework 4.1 DbContext使用记之一——如何查找实体? DbSet.Find函数的使用与实现 Entity Framework 4.1 DbContext使用记之二— ...
随机推荐
- docker实践-安装wordpress
很多人都有搭建wordpress的经历,可能被某些环境的配置搞得焦头乱耳的,这里使用docker,可以很轻松的进行wordpress的搭建工作. 安装 Docker sudo apt-get inst ...
- mailx发邮件报错Error initializing NSS: Unknown error -8015. . . . message not sent.处理
前提:在配置zabbix3.0监控发送邮件告警时zabbix界面显示邮件以送达,但是QQ邮箱却没有收到邮件,再shell命令行测试发邮件QQ邮箱又是可以收到的,在别人的提醒下用zabbix用户执行发送 ...
- 第12章 Reference-RIL运行框架
Reference-RIL完成两部分处理逻辑: 与LibRIL交互完成RIL消息的处理. 与Modem通信模块交互完成AT命令的执行. Reference-RIL的运行机制 主要涉及以下几个方面: R ...
- 初识Mybatis之工程搭建
简介:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 ...
- 千亿VR市场 将被国内厂商玩坏多少?
将被国内厂商玩坏多少?" title="千亿VR市场 将被国内厂商玩坏多少?"> 智能硬件行业在不断寻求新的突破口,当智能手机.平板.电视.家电等都司空见惯之后,能 ...
- Android长按及拖动事件探究
Android中长按拖动还是比较常见的.比如Launcher中的图标拖动及屏幕切换,ListView中item顺序的改变,新闻类App中新闻类别的顺序改变等.下面就这个事件做一下分析. 就目前而言,A ...
- C++扬帆远航——1
问题及代码: /* * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:test.cpp * 作者:常轩 * 完成日期:2 ...
- K-means真的不能使用曼哈顿距离吗?
问题 说到k-means聚类算法,想必大家已经对它很熟悉了,它是基于距离计算的经典无监督算法,但是有一次在我接受面试时,面试官问了我一个问题:“k-means为什么不能使用曼哈顿距离计算,而使用欧式距 ...
- KEMET推出新的多层陶瓷电容器,用于市电供电的应用
前言:2019年12月2日,全球领先的电子组件供应商KEMET公司 (“ KEMET”或“公司”)推出了一系列新的表面安装设备(SMD)安全认证的多层陶瓷电容器(MLCC),用于市电供电的应用.与现有 ...
- Dart的JIT 与 AOT
JIT:Just In Time AOT:Ahead of Time 含义: 目前,程序主要有两种运行方式:静态编译与动态解释. 静态编译的程序在执行前全部被翻译为机器码,通常将这种类型称为AOT ( ...