c# - 无法使用实体框架模型删除数据行
问题描述
我正在尝试删除我的应用程序中的一个项目。这就是我尝试在按钮单击事件中执行此操作的方式。首先,我检查该项目是否存在于数据库中,然后继续删除。
但是当我尝试删除时,我收到了这个错误:
一个实体对象不能被多个 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();
}
}
}
}
}
}
我该如何克服呢?
解决方案
您的实体已经被跟踪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();
推荐阅读
- python - Pandas & seaborn:如何根据预定义的标准对调查答案进行分类
- javascript - 如何以角度实现从url栏直接搜索?
- python - 迭代地将 numpy 或 torch 数组绘制为图像并打开按键
- mysql - 列计数与第 1 行的值计数不匹配 - MySQL
- javascript - 使用useState Hook时如何重构具有先前状态的if else if?
- python - 我需要在某个日期创建的所有子文件夹中找到所有文本文件,打开它们,然后将内容复制到一个文本文件中
- ag-grid - 我想将事件侦听器添加到 ag-grid 中的自定义列定义
- javascript - TypeError:无法读取未定义的属性“hasOwnProperty”
- javascript - StencilJs 组件不在另一个 stenciljs 项目中呈现
- c++ - 是什么导致了我的 C++ 程序中的 Stack Smashing 错误?