using (Session sess = BVVGlobal.oXpo.Get_Session()) { set_User o_u = BVVGlobal.oXpo.Get_Session().GetObjectByKey<set_User>(us.Oid); List<set_Org> orgList = new List<set_Org>(); // Список организаций orgList.Clear(); foreach (set_Org element in listBox2.Items) { orgList.Add(element); } while (o_u.Orgs.Count != 0) { int iy = o_u.Orgs.Count; o_u.Orgs.Remove(o_u.Orgs[iy - 1]); } for (int i = 0; i < orgList.Count; i++) { o_u.Orgs.Add(orgList[i]); } o_u.Save(); } 

Swears on o_u.Orgs.Add(orgList[i]) : says *.set_Org' object belongs to another session. How to fix?

  • BVVGlobal what BVVGlobal , oXpo and Get_Session() . Give a minimal reproducible example - Pavel Mayorov
  • @DukeSpontaneous - where did you get the word "compiler"? - Pavel Mayorov
  • @PavelMayorov from the error message. It is issued by XPO, Devexpress ORM. Although I could be wrong, of course. - andreycha
  • @PavelMayorov IDE? DevExpress is a set of various components, from UI controls to the ORM framework. - andreycha

1 answer 1

The reason for the error is that the code loads objects into two different sessions, and then the objects loaded in one session adds to the collection of objects loaded in another session. This is forbidden, because the session should monitor the state of the objects and be able at any time to answer the question, for example, which objects have been changed. Therefore, alien objects (loaded in another session) are rejected when trying to add them to the collection.

The exception points to the place in the code where it occurs, and the error message indicates its cause. In order to correct the error, you need to find the code that loads the objects involved in the operation, and modify it so that all the objects involved in the operation are loaded in one session.

If for any significant reason you cannot control the loading of objects and ensure that they are loaded in one session, then in order to add an object loaded in another session to the collection, you need to get the object loaded in the desired session using the Session.GetObjectByKey method. With this approach, changes that have not yet been saved will not be applied to the object loaded in another session. Therefore, this approach is not always applicable, and it is good practice to use only one session to load the objects required in the current operation.