0

I am trying to add new data to my database, here is my code:

// This is the dbContext
private BugTrackerDBContainer db = new BugTrackerDBContainer();

//The objet with its properties
public static Developper devAdded = new Developper();
devAdded.Name = txb_name.Text;
devAdded.FirstName = txb_firtname.Text;

// Add to the database
db.AddToDevelopper(devAdded);
db.SaveChanges();

My problem is that it I launch it once, it works fine, but twice I am having this error:

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

Why is it ?

Thanks for your helps

Cyril Gandon
  • 15,798
  • 12
  • 69
  • 116
dtjmsy
  • 2,386
  • 8
  • 37
  • 55
  • possible duplicate of [C# Entity Framework "An entity object cannot be referenced by multiple instances of IEntityChangeTracker"](http://stackoverflow.com/questions/5128361/c-sharp-entity-framework-an-entity-object-cannot-be-referenced-by-multiple-inst) – George Johnston Apr 24 '13 at 12:42
  • 'devAdded' object should not be static. – Kamil Krasinski Apr 24 '13 at 12:43

3 Answers3

2

What are all this mix of function and variables declaration?
You are trying to add the same static instance object twice to the same DataContext, it will fail.

  • Don't declare static variables. Is is bad.
  • Don't declare you Context as a field. Use it as a local variable with using blocks.
  • Don't mix access to UI element like textboxes with manipulation of database. Create layer in your application.

An example :

public void AddDevelopperButton_Click(object sender, EventArgs e)
{
    this.AddDevelopper(txb_name.Text, txb_firtname.Text);
}

public Developper AddDevelopper(string name, string firstName)
{
    Developper devAdded = new Developper();
    devAdded.Name = name;
    devAdded.FirstName = firstName;

    using(BugTrackerDBContainer db = new BugTrackerDBContainer())
    {
        db.AddToDevelopper(devAdded);
        db.SaveChanges();
    }
    return devAdded;
}
Cyril Gandon
  • 15,798
  • 12
  • 69
  • 116
  • Edit your question and post your entire code. What properties Developper as? Does it have a reference to another property? – Cyril Gandon Apr 24 '13 at 12:52
  • I miscopied the code, I tried it once again, works perfectly, cheers for your comments about the best practices, what to do and what not...thanks again – dtjmsy Apr 24 '13 at 12:54
0

You shouldn't have your database entity as a static object. The problem is most likely this line:

public static Developper devAdded = new Developper();

Change the code to what was recommended by @Scorpi0.

Garrett Vlieger
  • 8,965
  • 4
  • 30
  • 43
0

My suggestions are:

A: Learn basic programming

What possible reason declare static:

public static Developper devAdded = new Developper();

B: Then start looking into EF and other frameworks later.

Mark Homer
  • 609
  • 4
  • 11