EF中使用事务

using (var db = new dbEntities())
            {
                //第一个坑,需要手动open
                db.Database.Connection.Open();

                using (var tran = db.Database.Connection.BeginTransaction())
                {
                     //第二个坑,要自己创建command,然后把tran赋值给command
                    var commd= db.Database.Connection.CreateCommand();
                    commd.Transaction = tran;

                    string updateSql = "update tb_aaaaa set id = null,ScanManId=null,ScanDateTime=null where code in({0})".Format2("'{0}'".Format2(codeList.StringJoin("','")));
                    int count = 0;
                    try
                    {
                        commd.CommandText = updateSql;
                        count = commd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        return ex.Message;
                    }

                    if (count == 0)
                    {
                        tran.Rollback();
                        return "update影响行数为0";
                    }
                    if (count > 0 && count != codeList.Count)
                    {
                        tran.Rollback();
                        return "条码行数为{0},update行数{1},已回滚".Format2(codeList.Count, count);
                    }
                    tran.Commit();
                    return "成功";
                }
            }

 

posted @ 2021-11-12 15:31  212的s  阅读(98)  评论(0编辑  收藏  举报