EntityFramework用法探索(八)事务处理
使用 前文中描述的Retail示例 ,在Customer对象的Mapping中设置Name属性:
我们构造一个有效的Customer对象,再构造一个无效的Name属性为空的对象。
DomainModels.Customer customer1 = new DomainModels.Customer()
{
Name = "Dennis Gao",
Address = "Beijing",
Phone = "",
};
DomainModels.Customer customer2 = new DomainModels.Customer()
{
//Name = "Degang Guo", // 创造一个无效的对象,此处客户名称不能为空
Address = "Beijing",
Phone = "",
};
我们使用如下代码添加Customer对象数据到数据库中,
Customer entity1 = Mapper.Map<DomainModels.Customer, Customer>(customer1);
Customer entity2 = Mapper.Map<DomainModels.Customer, Customer>(customer2); using (RetailEntities context = new RetailEntities())
{
context.Customers.Add(entity1);
context.Customers.Add(entity2);
context.SaveChanges(); // 提交时将抛出异常 customer1.Id = entity1.Id;
customer2.Id = entity2.Id;
} Console.WriteLine(customer1);
Console.WriteLine(customer2);
EntityFramework已经明确的告诉我们某Entity验证失败。此时查询数据库,两条记录均不存在。EntityFramework自带的事务已经帮助回滚了操作。
现在我们修改下程序,改为提交两次:
try
{
using (RetailEntities context = new RetailEntities())
{
context.Customers.Add(entity1);
context.SaveChanges(); // 顺利执行
context.Customers.Add(entity2);
context.SaveChanges(); // 提交时将抛出异常 customer1.Id = entity1.Id;
customer2.Id = entity2.Id;
}
}
catch (Exception ex)
{
Console.WriteLine(FlattenException(ex));
}
然后我们修改代码,增加TransactionScope,
实例1
using (var transactionScope = new TransactionScope(
TransactionScopeOption.RequiresNew))
{
Customer entity1 = Mapper.Map<DomainModels.Customer, Customer>(customer1);
Customer entity2 = Mapper.Map<DomainModels.Customer, Customer>(customer2); using (RetailEntities context = new RetailEntities())
{
context.Customers.Add(entity1);
context.SaveChanges(); // 顺利提交
context.Customers.Add(entity2);
context.SaveChanges(); // 提交时将抛出异常 customer1.Id = entity1.Id;
customer2.Id = entity2.Id;
} transactionScope.Complete();
}
}
catch (Exception ex)
{
Console.WriteLine(FlattenException(ex));
}
实例2
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
{ //收藏
string collSql = @"delete from CollectDiscoverInfo where DiscoverID='{0}'"; collSql = string.Format(collSql, id);
db.Database.ExecuteSqlCommand(collSql); //评论
string commentSql = "delete from CommentDiscoverInfo where DiscoverID='{0}'";
commentSql = string.Format(commentSql, id);
db.Database.ExecuteSqlCommand(commentSql); //赞
string praiseSql = "delete from PraiseDiscover where DiscoverID='{0}'";
praiseSql = string.Format(praiseSql, id);
db.Database.ExecuteSqlCommand(praiseSql); //图片
string photoSql = "delete from DiscoverPhotoInfo where DiscoverID='{0}'"; photoSql = string.Format(photoSql, id);
db.Database.ExecuteSqlCommand(photoSql); //话题
db.DiscoverInfo.Remove(entity);
db.SaveChanges(); //提交事务
transactionScope.Complete();
}
EntityFramework用法探索(八)事务处理的更多相关文章
- .net EntityFramework用法探索系列 1
EntityFramework用法探索系列 (一)DatabaseFirst (二)CodeFirst (三)CodeFirst流畅API (四)Repository和UnitOfWork (五)引入 ...
- CoreCLR源码探索(八) JIT的工作原理(详解篇)
在上一篇我们对CoreCLR中的JIT有了一个基础的了解, 这一篇我们将更详细分析JIT的实现. JIT的实现代码主要在https://github.com/dotnet/coreclr/tree/m ...
- MongoDB 监控 --- MongoDB基础用法(八)
MongoDB 监控 在你已经安装部署并允许MongoDB服务后,你必须要了解MongoDB的运行情况,并查看MongoDB的性能.这样在大流量得情况下可以很好的应对并保证MongoDB正常运作. M ...
- EntityFramework DbContext 线程安全
先看这一段异常信息: A second operation started on this context before a previous asynchronous operation compl ...
- EntityFramework 中支持 BulkInsert 扩展
本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那 ...
- EntityFramework中支持BulkInsert扩展(转载)
前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那可能得用上个几分钟.EntityFramework 最被人诟病的地方就是它的性能,处理大量数据时的效 ...
- EntityFramework中支持BulkInsert扩展
EntityFramework中支持BulkInsert扩展 本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 Ent ...
- Manager(管理器)
Manager(管理器) 索引 意图 结构 参与者 适用性 效果 实现 实现方式(一):Manager 模式的示例实现. 意图 将对一个类的所有对象的管理封装到一个单独的管理器类中. 这使得管理职责的 ...
- Dapper ORM 用法—Net下无敌的ORM(转)
假如你喜欢原生的Sql语句,又喜欢ORM的简单,那你一定会喜欢上Dapper这款ROM.点击下载Dapper的优势:1,Dapper是一个轻型的ORM类.代码就一个SqlMapper.cs文件,编译后 ...
随机推荐
- html5 sessionStorage VS loaclStorage
localStorage:沒有時間限制的存儲,數據一致存在 sessionStorage:針對一個session的存儲,會話頁面關閉后,數據被刪除 以前這些都是通過cookie來完成的,但是cooki ...
- js運算符
運算符算術運算符.邏輯運算符.賦值運算符.比較運算符.條件運算符 字符串的合併,用+,如果是字符串和數字用+連接,則當做字符串合併. 條件運算符:if(條件)?語句1,語句2:
- PythonProject(1)vim的Hustoj插件
打算写一个vim的插件,或者emacs的插件.可以在编辑器里打比赛,看rank,交代码.总之相当于一个桌面版的hustoj 这是上学期就有的一个脑洞产物,昨天学了Python的爬虫,发现这个东西很有实 ...
- Pairs Forming LCM LightOJ - 1236 (算术基本定理)
题意: 就是求1-n中有多少对i 和 j 的最小公倍数为n (i <= j) 解析: 而这题,我们假设( a , b ) = n ,那么: n=pk11pk22⋯pkss, a=pd11pd2 ...
- Codeforces Round #410 (Div. 2) B
B. Mike and strings time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- 20 Zabbix 利用Scripts栏目对Hosts远程执行命令
点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 20 Zabbix 利用Scripts栏目对Hosts远程执行命令 在Monitoring板块中, ...
- 自学Aruba5.1.2-带宽限制
点击返回:自学Aruba之路 自学Aruba5.1.2-带宽限制 1 针对role --可以限制所有数据 注:带宽限制需要PEFNG许可证 单位可以是kbits或是mbits 可以是上传(up ...
- 配置AD RMS及SharePoint 2013 IRM问题解决及相关资源
最近配置AD RMS及SharePoint 2013 IRM遇到几个问题: 1. RMS配置好后,client端连不上, 一直要求输入用户名和密码. 后来换了台不是SP的机器,并用内部DB,搞定. ...
- json序列化 & 反序列化
json序列化: json的dumps方法可以将json格式数据序列为python的相关数据类型,比如str,常用于打印,另外,在序列化时,中文汉字被转换为unicode编码,在dumps函数中添加参 ...
- ??? cliquers
解:先推一个式子,然后就是CRT了... 那个阶乘怎么求呢?主要是分母可能有0,这时我们把分母的因子p全部提出来,上下次数相减判断即可. 细节颇多......注意在快速幂开始的时候a %= MO是个好 ...