首先在项目里面引用Transactions,如下图:
然后在控制器里面引用 using System.Transactions;
最后开始写代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Transactions;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
/// <summary>
/// TransactionScope事务:可自动提升事务为完全分布式事务的轻型(本地)事务。
/// 使用时要保证MSDTC服务(控制分布事务)是开启的可以使用:net start msdtc命令开启服务;
/// </summary>
public ActionResult Index()
{
using (TransactionScope sc = new TransactionScope())
{
try
{
using (feEntities db = new feEntities())
{
WorkTime wt = new WorkTime() { DayTime=DateTime.Now,LongTime=12 };
db.WorkTime.Add(wt);
db.SaveChanges();
//int dsa = 0;
//int sa =1/dsa;
}
sc.Complete();//放在catch上面,否则不能回滚
}
catch (Exception)
{
}
}
return View();
}
}
}