简体   繁体   中英

Why is my code triggering multiple DB context though I'm only using 1 context

Sorry if the code is a bit long. I only have one context. But I get the following error

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Below is the line that triggers it

Line 163: foreach (ligne l in SessionVariables.ligneNouvelleFacture)

Line 164: {

Line 165: dc.ligne.Add(l);

Line 166: }

So what I'm simply trying to do is to use EntityFramework context class default methods to insert data in the DB. The data is stored in a static list of object that I iterate with a foreach and add then in the context before saving the change dc.SaveChanges()

I don't know why I get that error since I have only create a single instance of the context in this webform behind code. And that same context varible is used to fill a gridview on page load.

Can you help me figure it out ? Below is my code

public class Utilities()
{
   public static list<object> myList = new list<object>();
}

public partial classe MyWebform : Page
{
   MyContext cnx = new MyContext();
   potected void Page_Load()
   { // Do something with the context "cnx" and static list of utilities class}

protected void button_Click(...)
{
   //Also do something with the context "cnx" and the static list of utilities class
}
}

UPDATE

After the anwser below and also after seeing Dispose on MSDN and reading Entity Framework and context dispose , I tried a new approach which seems to be working. Hopefully it's not too bad. I maybe wrongly implementing using but it seems it does not dispose implicitly.

public class  MyWebForm .....
{
  // I do no declare a context variable object so that every time a context must be used, I do the following.

  using (MyContext cnx = new MyContext())
  {
     // ...do something with cnx
     cnx.Dispose();  // This line appears to be compulsory to avoid multiple context error
  }
}

Hopefully this helps someone

You are creating multiple contexts. Every time a page is loaded a new one is created. You keep a static list of objects and then try to add them again and again to a context, even when they already are in one. This will cause an error.

This may also cause a memory leak since every object has a separate context which cannot be released due to the objects being alive. You should redesign the functionality. Is it necessary to keep the objects in memory? Why do you need to add all objects into the context again and not just the new ones?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM