EF事务的使用
一、SaveChanges自带事务
using (TencentClassRoomContext context = new TencentClassRoomContext())
{
{
var userlist = context.SysUsers.Where(a => a.Id > 3).ToList();
var user = context.SysUsers.Find(5);
}
{
Company adCompany001 = new Company()
{
Name = "测试一下公司0001"
};
context.Companies.Add(adCompany001);
Company adCompany002 = new Company()
{
Name = "测试一下公司0002~~"
};
context.Companies.Add(adCompany002);
}
{
SysLog updatlog = context.SysLogs.Find(1);
updatlog.Introduction += "---ABCDEFG";
}
{
SysLog removelog2 = context.SysLogs.Find(2);
context.SysLogs.Remove(removelog2);
}
context.SaveChanges();
}
二、EF执行sql 事务
using (TencentClassRoomContext dbContext = new TencentClassRoomContext())
{
{
DbContextTransaction trans = null;
try
{
trans = dbContext.Database.BeginTransaction();
string sql = "Update [SysUser] Set Name='Richard-0001' WHERE Id=@Id";
SqlParameter parameter = new SqlParameter("@Id", 1);
dbContext.Database.ExecuteSqlCommand(sql, parameter);
SysLog updatlog = dbContext.SysLogs.Find(1);
updatlog.UserName = "————————";
updatlog.Introduction += "---ABCDEFG";
dbContext.SaveChanges();
trans.Commit();
}
catch (Exception ex)
{
if (trans != null)
trans.Rollback();
throw ex;
}
finally
{
trans.Dispose();
}
}
}
三、分布式事务
using (TencentClassRoomContext dbContext1 = new TencentClassRoomContext())
using (TencentClassRoomContext dbContext2 = new TencentClassRoomContext())
{
using (TransactionScope trans = new TransactionScope())
{
SysLog updatlog = dbContext1.SysLogs.Find(1);
updatlog.UserName = "ABCDAAA————————";
updatlog.Introduction += "---ABCDEFG";
dbContext1.SaveChanges();
SysLog updatlog2 = dbContext2.SysLogs.Find(1);
updatlog2.UserName = "测试一下~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~·";
updatlog2.Introduction += "---ABCDEFG";
dbContext2.SaveChanges();
trans.Complete();
}
}
四、封装
public class UnitOfWork
{
public static void Invoke(Action action)
{
TransactionScope transaction = null;
try
{
transaction = new TransactionScope();
action.Invoke();
transaction.Complete();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
UnitOfWork.Invoke(() =>
{
using (IUserCompanyService iUserCompanyService = new UserCompanyService(new JDDbContext()))
{
}
});