继续为想使用Entity Framework的朋友在前面探路,分享的东西虽然技术含量不高,但都是经过实践检验的。

在Entity Framework中使用事务很简单,将操作放在TransactionScope中,并通过Complete()方法提交事务即可。

示例代码如下:

using (BlogDbContext context =new BlogDbContext())
{
using (TransactionScope transaction =new TransactionScope())
{
context.BlogPosts.Add(blogPost);
context.SaveChanges();
postBody.ID
= blogPost.ID;
context.EntryViewCounts.Add(
new EntryViewCount() { EntryID = blogPost.ID });
context.PostBodys.Add(postBody);
context.SaveChanges();
//提交事务
transaction.Complete();
}
}

经过测试验证,在transaction.Complete()之前的代码中只要出现异常,事务就会回滚。

【更新】

更好的解决方法见 Working with Transactions (EF6 Onwards)

相关文章:

  • 2022-01-15
  • 2021-09-26
  • 2021-12-11
  • 2022-12-23
  • 2021-07-15
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-30
  • 2021-08-02
  • 2021-10-06
  • 2021-11-30
相关资源
相似解决方案