在Entity Framework中使用事务

继续为想使用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()之前的代码中只要出现异常,事务就会回滚。
原文地址:https://www.cnblogs.com/hyl8218/p/2205513.html