简体   繁体   中英

An entity object cannot be referenced by multiple instances of IEntityChangeTracker. What does it mean?

I've read many topics about this problem, but I still cant understand why I get this error.
Throws the error mentioned in the title: db.megrendelesek.Add(form.uj);

private void button1_Click(object sender, EventArgs e)
{
    foreach (Account item in db.accountok)
    {
        if (item.Username == textBox1.Text && item.Password == textBox2.Text)
        {
            MegrendelesForm form = new MegrendelesForm(item as Account);

            if (form.ShowDialog() == DialogResult.OK)
            {
                db.megrendelesek.Add(form.uj);

                db.SaveChanges();
            }
        }
        else
        {
            MessageBox.Show("Bad user or pw");
        }
    }
}

public partial class MegrendelesForm : Form
{
    RaktarDB db = new RaktarDB();
    public Megrendeles uj { get; set; }
    public Account belepett = new Account();

    public MegrendelesForm(Account item)
    {
        InitializeComponent();
        belepett = item;

        var aruk = (from aru in db.aruk
                select aru).ToList<Aru>();
        listBox1.DataSource = aruk;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        List<Aru> aruk = new List<Aru>();
        foreach (Aru item in listBox2.Items)
        {
            aruk.Add(item);
        }

        uj = new Megrendeles {account=belepett,aruk=aruk };
    }
    public class Megrendeles
    {
        public int ID { get; set; }
        public virtual Account account { get; set; }
        public virtual List<Aru> aruk { get; set; }
    }
}

This error normally comes from maintaining two contexts and trying to attach an entity from one to another context.

In your above example i cant really tell why this is the case but i imagine form.uj is populated from another instance of whatever db is.

Its normally sensible to share a context with all of your UI elements and this will probably resolve your issue.

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