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