积极答复者
entity framework框架使用事务当中出现的奇怪问题

问题
-
不知道大家有没有遇到过这种问题,比如我一开始某个字段太短了,第一次保存的时候会报错,然后回滚,接着我去数据库当中手动修改这个字段的长度,第二次保存可以成功,但是问题是,会把第一次失败的数据也一起保存进去,不知道如何解决,我一开始以为是我没有把连接关闭,但是后来加了也不可以,请大家帮我看一下,多谢!
int flag = -1; if (this.DbEntity.Connection.State != System.Data.ConnectionState.Open) { this.DbEntity.Connection.Open(); } var trans = this.DbEntity.Connection.BeginTransaction(); try { //这里进行添加数据操作 begin BT_RAILROADDOC_OP newObject = new BT_RAILROADDOC_OP(); newObject.RLOP_ID = Guid.NewGuid(); newObject.RLOP_EXPECTED_AMOUT = obj.RLOP_EXPECTED_AMOUT; newObject.RLOP_EXPECTED_PACK = obj.RLOP_EXPECTED_PACK; newObject.RLOP_FROM = obj.RLOP_FROM; newObject.RLOP_INOUT_NUM = obj.RLOP_INOUT_NUM; newObject.RLOP_INPUT_DATE = obj.RLOP_INPUT_DATE; newObject.RLOP_INPUT_USERID = obj.RLOP_INPUT_USERID; newObject.RLOP_OPDATE = obj.RLOP_OPDATE; newObject.RLOP_OPDEPARTMENT_ID = obj.RLOP_OPDEPARTMENT_ID; newObject.RLOP_RLRD_ID = obj.RLOP_RLRD_ID; newObject.RLOP_TO = obj.RLOP_TO; this.DbEntity.AddToBT_RAILROADDOC_OP(newObject); //end this.DbEntity.SaveChanges(); trans.Commit(); flag = 0; } catch (Exception ex) { //比如我第一次保存失败,会回滚,数据库当中也不会添加数据, //但是比如我修改了一下数据,第二次可以正常保存数据,但是发现数据库当中会有两条相同的数据,也就是savechange的时候 //把上一次失败时的数据也一起保存进去了 trans.Rollback(); throw ex; } finally { if (this.DbEntity.Connection.State != System.Data.ConnectionState.Closed) { this.DbEntity.Connection.Close();//一开始我以为是这里没有把连接关闭,后来加上也不可以 } } return flag;
crazyBasketball
答案
-
参考How to reset change tracking (ObjectStateManager)
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
Visual C++ MVP- 已标记为答案 Mog Liang 2010年8月13日 5:31
全部回复
-
ObjectContext会跟踪你所做的改动。你保存失败的话添加的数据仍旧处于已添加状态。
PS SaveChanges自动建立一个事务的。
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
Visual C++ MVP -
是啊,所以你只有一个savechange的话没有必要自己创建事务的。
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
Visual C++ MVP -
参考How to reset change tracking (ObjectStateManager)
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
Visual C++ MVP- 已标记为答案 Mog Liang 2010年8月13日 5:31