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

问题描述 投票:0回答:1

[当我尝试更改数据库中的数据时,将引发异常。我是Entity的新手,请不要怀疑如何解决它。我使用MS SQL Server。使用代码优先和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();

                }
}

类上下文

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; }
    }
c# visual-studio entity-framework-6 ef-code-first .net-4.8
1个回答
0
投票

似乎您从某种数据网格中获取了Circular c = DG_C.CurrentRow.DataBoundItem as Circular;,而该数据网格是使用一种不同的上下文填充的,而不是使用一种获取此Red_Circular red = context.Reds.SingleOrDefault(r => r.Circular__ID == c.ID_Circular);的数据网格。

尝试在您的课程中使用一个全局上下文,然后使用该全局上下文填充您的网格并获取您的Red_Circular

那个有灵魂的人解决了

© www.soinside.com 2019 - 2024. All rights reserved.