Entity Framework 的事务 DbTransaction

来源:互联网 发布:中公教育网络课程 编辑:程序博客网 时间:2024/05/29 12:58
复制代码
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 == 20);    st.StudentName = "test";    st.Age = 55;    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();    }    }}
复制代码
0 0