• Entity Framework 6.0 Tutorials(6):Transaction support


    Transaction support:

    Entity Framework by default wraps Insert, Update or Delete operation in a transaction, whenever you execute SaveChanges(). EF starts a new transaction for each operation and completes the transaction when the operation finishes. When you execute another such operation, a new transaction is started.

    EF 6 has introduced database.BeginTransaction and Database.UseTransaction to provide more control over transactions. Now, you can execute multiple operations in a single transaction as shown below:

    using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction( ))
    {
            try
            {
                Student std1 = new Student() { StudentName = "newstudent" };
                context.Students.Add(std1);
                context.Database.ExecuteSqlCommand(
                    @"UPDATE Student SET StudentName = 'Edited Student Name'" +
                        " WHERE StudentID =1"
                    );
                context.Students.Remove(std1);
    
                //saves all above operations within one transaction
                context.SaveChanges();
    
                //commit transaction
                dbTran.Commit();
            }
            catch (Exception ex)
            {
                //Rollback transaction if exception occurs
                dbTran.Rollback();
            }
    
    }

    database.UseTransaction allows the DbContext to use a transaction which was started outside of the Entity Framework.

    Download DB First sample project for Transactions demo.

  • 相关阅读:
    第09组 Alpha冲刺 (2/6)
    第08组 Beta冲刺 (1/5)
    第08组 Alpha冲刺 总结
    第08组 Alpha冲刺 (6/6)
    第08组Alpha冲刺(5/6)
    第08组 Alpha冲刺 (4/6)
    第08组 Alpha冲刺 (3/6)
    第08组 Alpha冲刺 (2/6)
    第08组 Alpha冲刺 (1/6)
    第12组 Beta冲刺(2/5)
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5649547.html
Copyright © 2020-2023  润新知