使用 前文中描述的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用法探索(八)事务处理的更多相关文章

  1. .net EntityFramework用法探索系列 1

    EntityFramework用法探索系列 (一)DatabaseFirst (二)CodeFirst (三)CodeFirst流畅API (四)Repository和UnitOfWork (五)引入 ...

  2. CoreCLR源码探索(八) JIT的工作原理(详解篇)

    在上一篇我们对CoreCLR中的JIT有了一个基础的了解, 这一篇我们将更详细分析JIT的实现. JIT的实现代码主要在https://github.com/dotnet/coreclr/tree/m ...

  3. MongoDB 监控 --- MongoDB基础用法(八)

    MongoDB 监控 在你已经安装部署并允许MongoDB服务后,你必须要了解MongoDB的运行情况,并查看MongoDB的性能.这样在大流量得情况下可以很好的应对并保证MongoDB正常运作. M ...

  4. EntityFramework DbContext 线程安全

    先看这一段异常信息: A second operation started on this context before a previous asynchronous operation compl ...

  5. EntityFramework 中支持 BulkInsert 扩展

    本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那 ...

  6. EntityFramework中支持BulkInsert扩展(转载)

    前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那可能得用上个几分钟.EntityFramework 最被人诟病的地方就是它的性能,处理大量数据时的效 ...

  7. EntityFramework中支持BulkInsert扩展

    EntityFramework中支持BulkInsert扩展 本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 Ent ...

  8. Manager(管理器)

    Manager(管理器) 索引 意图 结构 参与者 适用性 效果 实现 实现方式(一):Manager 模式的示例实现. 意图 将对一个类的所有对象的管理封装到一个单独的管理器类中. 这使得管理职责的 ...

  9. Dapper ORM 用法—Net下无敌的ORM(转)

    假如你喜欢原生的Sql语句,又喜欢ORM的简单,那你一定会喜欢上Dapper这款ROM.点击下载Dapper的优势:1,Dapper是一个轻型的ORM类.代码就一个SqlMapper.cs文件,编译后 ...

随机推荐

  1. angular2+中数据变更子组件页面未更新

    引入监测 import {ChangeDetectorRef} from '@angular/core'; constructor( private changeDetectorRef:ChangeD ...

  2. python 判断变量有没有定义

    ? 1 2 'varname' in locals().keys() 'varname' in  dir()

  3. Lodop导出excel及提示成功【回调和直接返回值】

    高版本的火狐和谷歌不再支持np插件之后,Lodop公司推出了C-Lodop,解决了这些浏览器不能用Lodop插件方式打印的问题,相比较Lodop插件,C-Lodop由于是以服务的形式出现,返回值不能直 ...

  4. day29 __eq__ 比较

    本质上 "==" 调用的内部方法就是 __eq__() 正常情况下,两个名字相同的变量比较的是内存地址,内存地址当然是不一样的可以使用__eq__来改变成名字相同就相等 1 cla ...

  5. mysql test== 坑

    错误 <if test="status == '1'"> 正确 <if test="status == '1'.toString()">

  6. 【转】安全加密(三):RFID标签防伪为生活开启安全模式

    本文导读 随着RFID技术的快速发展和RFID电子标签的生产成本不断降低,RFID标签防伪技术的应用也得到了极大的普及,逐步出现在各行各业当中,如交通出行.票务安全.商品防伪等领域. RFID技术简介 ...

  7. Elasticsearch 常见问题的解决思路

    本文为es性能监控基础的扩展,大家可以先看下性能监控基础,熟悉下es的基本原理.为翻译性质文档,感谢原作者,原始文档地址 类似于汽车的运行方式,Elasticsearch旨在让用户快速上手和运行,而无 ...

  8. Android 屏幕手势滑动中onFling()函数的技巧分析

    关于如何处理手势操作以及那四个基本固定的顺序我就不讲解了,这里直接跳到我们获得瞬间滑动后回调onFling()这个抽象函数时,应该如何根据参数比较准确的判断滑动方向.如果你没有前面的基础知识,你可以去 ...

  9. HDU 3338 Kakuro Extension (网络流,最大流)

    HDU 3338 Kakuro Extension (网络流,最大流) Description If you solved problem like this, forget it.Because y ...

  10. switch查询成绩、公司年销售额求和、根据工龄求工资

    /* 1 编写代码实现如下内容:if语句实现考试成绩分等级(使用switch语句). [90-100] A等. [80-90) B等. [70-80) C等. [60-70) D等. [0-60) E ...