Entity Framework 的事务 DbTransaction

时间:2023-03-08 22:16:08
Entity Framework 的事务 DbTransaction

事务代码实现如下:

public static void Transaction()
{
myitEntities entity = null;
DbTransaction tran = null;
try
{
entity = new myitEntities();
entity.Connection.Open();
tran = entity.Connection.BeginTransaction();
Student st = entity.Student.FirstOrDefault(c => c.StudentID == );
st.StudentName = "test";
st.Age = ;
entity.SaveChanges();
// 提交事务
tran.Commit(); }
catch (Exception ex)
{
if (tran != null)
{
// 事务回滚
tran.Rollback();
Console.WriteLine("事务回滚");
throw ex;
}
}
finally {
if (entity != null && entity.Connection.State != ConnectionState.Closed)
{
entity.Connection.Close();
}
}
}