无法使用实体框架模型删除数据行

时间:2018-12-09 12:49:31

标签: c# entity-framework object delete-row

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

但是当我尝试删除时,出现此错误:

  

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 个答案:

答案 0 :(得分:2)

您的实体已被Logcat跟踪(因此出现错误),因此您不需要第二次DbContest。只需替换:

RAE

使用

// 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();
  }
}