private static void TestTransaction2() { using (var db = MyDB.GetDBHelper()) { EntityQuery <AuctionOperationLog> query = new EntityQuery <AuctionOperationLog>(db); AuctionOperationLog optLog = new AuctionOperationLog(); optLog.OperaterID = 1000; optLog.Module = "Login"; optLog.Operation = "登录成功2"; optLog.LogSource = "PC"; //开启事务 db.BeginTransaction(); int count = query.Insert(optLog); //模拟数据操作失败,抛出异常 if (count > 0) { //throw new Exception("测试在事务过程中数据操作异常"); Console.WriteLine("测试在事务过程中数据操作异常 退出"); return; } //必须设置为全部属性已经修改,否则仅会更新 Operation 字段 optLog.ResetChanges(true); optLog.Operation = "退出登录"; query.Insert(optLog); db.Commit(); } }
private static void TestTransaction() { AdoHelper db = MyDB.GetDBHelper(); EntityQuery <AuctionOperationLog> query = new EntityQuery <AuctionOperationLog>(db); AuctionOperationLog optLog = new AuctionOperationLog(); optLog.OperaterID = 1000; optLog.Module = "Login"; optLog.Operation = "登录成功1"; optLog.LogSource = "PC"; db.BeginTransaction(); try { query.Insert(optLog); //必须设置为全部属性已经修改,否则仅会更新 Operation 字段 optLog.ResetChanges(true); optLog.Operation = "退出登录"; query.Insert(optLog); //optLog.Module = "Login"; //OQL q = OQL.From(optLog).Select().Where(optLog.Module).END; OQL q = new OQL(optLog); //q.Select().Where(q.Condition.AND(optLog.Operation, "like", "%登录%")); q.Select().Count(optLog.OperaterID, "");//使用空字符串参数,这样统计的值将放到 OperaterID 属性中 //必须指定db参数,否则不再一个事务中,无法进行统计查询 optLog = EntityQuery <AuctionOperationLog> .QueryObject(q, db); int allCount = optLog.OperaterID; //optLog 已经使用过,在生成OQL的查询前,必须使用新的实体对象, // 否则下面的查询仅会使用OperaterID 字段从而导致分页查询出错 optLog = new AuctionOperationLog(); q = new OQL(optLog); q.Select().OrderBy(optLog.Module, "asc").OrderBy(optLog.AtDateTime, "desc"); q.Limit(10, 2); q.PageEnable = true; q.PageWithAllRecordCount = allCount; //查询列表并更新到数据库 List <AuctionOperationLog> list = EntityQuery <AuctionOperationLog> .QueryList(q, db); foreach (AuctionOperationLog logItem in list) { logItem.AtDateTime = DateTime.Now; } query.Update(list); db.Commit(); Console.WriteLine("事务操作成功。"); } catch (Exception ex) { Console.WriteLine("Error:" + ex.Message); db.Rollback(); } }