首页 > 解决方案 > 无法使用实体框架模型删除数据行

问题描述

我正在尝试删除我的应用程序中的一个项目。这就是我尝试在按钮单击事件中执行此操作的方式。首先,我检查该项目是否存在于数据库中,然后继续删除。

但是当我尝试删除时,我收到了这个错误:

一个实体对象不能被多个 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();
                    }
                }
            }
        }                
    }          
}

我该如何克服呢?

标签: c#entity-frameworkobjectdelete-row

解决方案


您的实体已经被跟踪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();

推荐阅读