首页 文章

无法使用Entity Framework模型删除数据行

提问于
浏览
0

我正在尝试删除我的应用程序中的项目 . 这就是我在按钮点击事件中尝试这样做的方法 . 首先,我检查数据库中是否存在该项目,然后继续删除 .

但是当我尝试删除时,我收到此错误:

IEntityChangeTracker的多个实例无法引用实体对象 .

我的代码:

private void btnRemove_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Do you want to proceed with deleting?", "System Alert", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        int jid = 0;
        int ProdLine = 0;
        int seritid = 0;

        if (dgvServices.SelectedRows.Count != 0)
        {
            DataGridViewRow row = this.dgvServices.SelectedRows[0];
            jid = Convert.ToInt32(row.Cells["JID"].Value.ToString());
            ProdLine = Convert.ToInt32(row.Cells["ProdLine"].Value.ToString());
            seritid = Convert.ToInt32(row.Cells["ServiceItem"].Value.ToString());
        }

        using (DataControllers.RIT_Allocation_Entities RAE = new DataControllers.RIT_Allocation_Entities())
        {
            jsmodel2 = RAE.Job_Service.Where(a => a.JID == jid && a.ProdLine == ProdLine && a.ServiceItem == seritid).OrderByDescending(x => x.ServiceItem) 
                                      .Take(1).FirstOrDefault();

            if (jsmodel2 == null)
            {
                // No service item exists for this
                // Nothing to delete
                MessageBox.Show("The item doesn't exist ","Alert");
                return;
            }
            else
            {
                // Delete
                using (DataControllers.RIT_Allocation_Entities RAEE = new DataControllers.RIT_Allocation_Entities())
                {
                    var entry = RAEE.Entry(jsmodel2);

                    if (entry.State == EntityState.Detached)
                    {
                        RAEE.Job_Service.Attach(jsmodel2);
                        RAEE.Job_Service.Remove(jsmodel2);
                        RAEE.SaveChanges();
                        populateServiceDetailsGrid();
                    }
                }
            }
        }                
    }          
}

我怎么能克服这个?

1 回答

  • 2

    您的实体已被 RAE 跟踪(因此错误),因此您不需要第二个DbContest . 简单地替换:

    // Delete
    using (DataControllers.RIT_Allocation_Entities RAEE = new DataControllers.RIT_Allocation_Entities())
    {
      var entry = RAEE.Entry(jsmodel2);
    
      if (entry.State == EntityState.Detached)
      {
        RAEE.Job_Service.Attach(jsmodel2);
        RAEE.Job_Service.Remove(jsmodel2);
        RAEE.SaveChanges();
        populateServiceDetailsGrid();
      }
    }
    

    RAE.Job_Service.Remove(jsmodel2);
     RAE.SaveChanges();
     populateServiceDetailsGrid();
    

相关问题