【问题标题】:Entity Framework the delete statement conflicted with the reference constraint实体框架删除语句与引用约束冲突
【发布时间】:2015-08-16 01:28:31
【问题描述】:

我有两个表 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;
   }
}

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

完整的错误在这里:

DELETE 语句与 REFERENCE 约束冲突 “FK_Bill_Employee”。数据库发生冲突 “myDatabase”,表“dbo.Bill”,列“idEmployeeMember”。
声明已终止。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

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

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

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

    下次当您加载该员工所属的特定商店时,该员工将不再出现在该商店的员工集合中 - 无需进行任何杂乱的手动删除或任何操作......

    【讨论】:

    • 没什么。这是一个主键不为空的简单表。但是,如果我尝试删除 idStore = 1 的员工,那么如果在 Store 表中只有一行 idStore=1,则应将其删除。我认为这就是发生此错误的原因。
    • {"DELETE 语句与 REFERENCE 约束 \"FK_Bill_Employee\" 冲突。冲突发生在数据库 \"myDatabase\"、表 \"dbo.Bill\"、列 'idEmployeeMember' 中。\ r\n语句已终止。"}
    • @Srcee: READ THE ERROR MESSAGE!! 显然,BILLEMPLOYEE 之间必须有一个引用,您没有提到任何地方,这就是问题所在!从该消息中,很明显EmployeeStore 之间的问题不是 - 但是有一个表Bill 的列idEmployeeMember 仍然引用您正在尝试的员工删除.......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多