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();
}
 
上一篇:201621123001 《Java程序设计》第12周学习总结


下一篇:CocoaPods本身版本的更新