EF 不允许启动新事务,因为有其他线程正在该会话中运行。

时间:2022-05-25 23:37:55

引起原因:在查询中提交了更改。如在遍历的时候,调用了savechanges();

解决:把savechange()提到循环外.          

 

IOrderedQueryable<TOHOSPITAL_TBL> tb = ent.TOHOSPITAL_TBL.Where(record =>
                    (record.TOHOSPITAL_STATE_TYPE_TBL.VALUE == (int)ToHospitolState.treatment) ||
                    (record.TOHOSPITAL_STATE_TYPE_TBL.VALUE == (int)ToHospitolState.Clinic)).
                        OrderByDescending(record => record.TOHOSPITAL_TIME);
                foreach (TOHOSPITAL_TBL tohospotal in tb)
                {
                    if (!tohospotal.TOHOSPITAL_STATE_TYPE_TBLReference.IsLoaded)
                    {
                        tohospotal.TOHOSPITAL_STATE_TYPE_TBLReference.Load();
                    }
                    ChangeState(tohospotal);
               ent.SaveChanges();
                }
原因IOrderedQueryable<TOHOSPITAL_TBL> tb还在查询中,调用ent.SaveChanges();产生的。

ent.SaveChanges();提出即可

代码:

                IOrderedQueryable<TOHOSPITAL_TBL> tb = ent.TOHOSPITAL_TBL.Where(record =>
                    (record.TOHOSPITAL_STATE_TYPE_TBL.VALUE == (int)ToHospitolState.treatment) ||
                    (record.TOHOSPITAL_STATE_TYPE_TBL.VALUE == (int)ToHospitolState.Clinic)).
                        OrderByDescending(record => record.TOHOSPITAL_TIME);
                foreach (TOHOSPITAL_TBL tohospotal in tb)
                {
                    if (!tohospotal.TOHOSPITAL_STATE_TYPE_TBLReference.IsLoaded)
                    {
                        tohospotal.TOHOSPITAL_STATE_TYPE_TBLReference.Load();
                    }
                    ChangeState(tohospotal);
                }
                ent.SaveChanges();