码迷,mamicode.com
首页 > 数据库 > 详细

Entity Framework 的事务 DbTransaction

时间:2014-12-31 18:16:25      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

事务代码实现如下:

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();
    }
    }
}

 

Entity Framework 的事务 DbTransaction

标签:

原文地址:http://www.cnblogs.com/xgao/p/4196168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!