使用代码优先和 EntityFramework 6 ,WFA 的 IEntityChangeTracker 的多个实例不能引用一个实体对象

An entity object cannot be referenced by multiple instances of IEntityChangeTracker using code-first and EntityFramework 6 ,WFA

当我尝试更改数据库中的数据时,出现异常。我是 Entity 的新手,不了解如何修复它。我使用 MS SQL 服务器。使用代码优先和 EntityFramework 6 ,WFA.

方法

private void editCircularToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Circular c = DG_C.CurrentRow.DataBoundItem as Circular;
            MyContext context = new MyContext();
            Red_Circular red = context.Reds.SingleOrDefault(r => r.Circular__ID == c.ID_Circular);
            AddCircular add = new AddCircular();
            add.tbsur.Text = c.Surname;
            add.tbname.Text = c.Name;
            add.cbeye.Text = c.EyeColor;                           // adding values to the textboxes on anoter forms
            add.cbhair.Text = c.HairColor;                         // добавление значение в тексбоксы другой формы

            if (red != null)// if found если найдено
            {
                add.tbchange.Text = red.charge;
                DialogResult result = add.ShowDialog(this);
                if (result == DialogResult.Cancel)
                {
                    c.Surname = add.tbsur.Text;
                    c.Name = add.tbname.Text;

                    c.EyeColor = add.cbeye.Text;
                    c.HairColor = add.cbhair.Text; // adding new values добавления новых значений
                    c.Activity = true;
                    red.charge = add.tbchange.Text;
                    red.info = add.tbinfo.Text;
                    context.Entry(c).State = EntityState.Modified; // error ошибка
                    //An entity object cannot be referenced by multiple instances of IEntityChangeTracker
                    context.Entry(red).State = EntityState.Modified;// if you delete 
                    //the line abode then this line works

                    context.SaveChanges();

                }
}

Class 上下文

public class MyContext : DbContext
    {
        public MyContext() : base("DefaultConnection")
        {

        }
        public DbSet<Department> Departments { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Resualt_of_search> Resualts { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Circular> Circulars { get; set; }
        public DbSet<Red_Circular> Reds { get; set; }
        public DbSet<Blue_Circular> Blues { get; set; }
        public DbSet<Black_Circular> Blacks { get; set; }
        public DbSet<Yellow_circular> Yellows { get; set; }
        public DbSet<Green_Circular> Greens { get; set; }
    }

您的 Circular c = DG_C.CurrentRow.DataBoundItem as Circular; 似乎是从某种数据网格中获取的,该数据网格使用与您使用的获取此 Red_Circular red = context.Reds.SingleOrDefault(r => r.Circular__ID == c.ID_Circular);

的上下文不同的上下文填充

尝试在您的 class 中使用一个全局上下文,然后使用它来填充您的网格并获得您的 Red_Circular

那个灵魂可以解决它