简体   繁体   中英

Add new data with Entity Framework

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

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;
}

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.

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.

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