gpt4 book ai didi

entity-framework - Entity Framework 删除语句与引用约束冲突

转载 作者:行者123 更新时间:2023-12-03 07:27:08 25 4
gpt4 key购买 nike

我有两个表 Employee (n) 和 Store (1),它们具有 n:1 关系。

Employee 具有外键 idStore,它是来自 Store 的主键。

以下是我尝试从Employee删除行的方法:

public void deleteEmployee(int idEmployee)
{
MyEntities pe = new MyEntities();
try
{
var firstQuery = from e in pe.Employees
where e.idEmployee == idEmployee
select e;
string findIdStore = firstQuery.First().StoreReference.EntityKey.EntityKeyValues[0].Value.ToString();
int idStore = Int32.Parse(findIdStore);
Store r = pe.Stores.First(c => c.idStore == idStore);
r.Employees.Remove(firstQuery.First());
pe.DeleteObject(firstQuery.First());
pe.SaveChanges();
}
catch (Exception ex)
{
return;
}
}

而且,我仍然收到删除语句与引用约束冲突的错误。

完整的错误在这里:

The DELETE statement conflicted with the REFERENCE constraint "FK_Bill_Employee". The conflict occurred in database "myDatabase", table "dbo.Bill", column 'idEmployeeMember'.
The statement has been terminated.

最佳答案

你不能找到并删除该员工吗?

public void deleteEmployee(int idEmployee)
{
using(MyEntities pe = new MyEntities())
{
var emmployeeToDelete = pe.Employees.FirstOrDefault(e => e.idEmployee == idEmployee);

if(employeeToDelete != null)
{
pe.DeleteObject(employeeToDelete);
pe.SaveChanges();
}
}
}

我认为你不需要做更多的事情,真的......

下次当您加载该员工所属的这个特定商店时,该员工将不再位于该商店的员工集合中 - 无需进行任何困惑的手动删除或任何操作......

关于entity-framework - Entity Framework 删除语句与引用约束冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8637448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com