C# 实体框架错误消息DbUpdateException
作为作业的一部分,我必须使用实体框架创建一个web应用程序。我现在正在学习教程 共有四个表:C# 实体框架错误消息DbUpdateException,c#,database,entity-framework-6,C#,Database,Entity Framework 6,作为作业的一部分,我必须使用实体框架创建一个web应用程序。我现在正在学习教程 共有四个表:分行、部门、员工和职位 创建了一个方法来对数据进行种子设定后,我已在调试模式下运行应用程序,并收到以下错误消息: System.Data.Entity.Infrastructure.DbUpdateException:'更新条目时出错。有关详细信息,请参见内部异常。“SqlException:INSERT语句与外键约束“FK_dbo.Employee_dbo.Branch_BranchId”冲突。冲突发生
分行
、部门
、员工
和职位
创建了一个方法来对数据进行种子设定后,我已在调试模式下运行应用程序,并收到以下错误消息:
System.Data.Entity.Infrastructure.DbUpdateException:'更新条目时出错。有关详细信息,请参见内部异常。“SqlException:INSERT语句与外键约束“FK_dbo.Employee_dbo.Branch_BranchId”冲突。冲突发生在数据库“HumanResourcesWebApp1”、表“dbo.Branch”、列“ID”中。声明已终止
我已经研究了这条信息,但我没有遵循我找到的答案。如果能给我一些指导,我将不胜感激。如果有帮助的话,我还会添加类的结构。我知道当员工
表将分支
表的主键视为外键时,问题出现在主键之间,但我不知道在何处进行更改
分支机构:
public int ID { get; set; }
public string Address { get; set; }
public int DepartmentID { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public int ID { get; set; }
public string DepartmentName { get; set; }
public string DepartmentFunction { get; set; }
public virtual ICollection<Branch> Branches { get; set; }
public int ID { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public double Salary { get; set; }
public DateTime StartingDate { get; set; }
public int BranchId { get; set; }
public int TitleId { get; set; }
public int ID { get; set; }
public string TitleName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
标题:
public int ID { get; set; }
public string Address { get; set; }
public int DepartmentID { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public int ID { get; set; }
public string DepartmentName { get; set; }
public string DepartmentFunction { get; set; }
public virtual ICollection<Branch> Branches { get; set; }
public int ID { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public double Salary { get; set; }
public DateTime StartingDate { get; set; }
public int BranchId { get; set; }
public int TitleId { get; set; }
public int ID { get; set; }
public string TitleName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public int ID{get;set;}
公共字符串标题名{get;set;}
公共虚拟ICollection雇员{get;set;}
提前感谢您正在尝试保存引用不存在分支机构的员工详细信息。这可能是因为您根本没有设置分支id,或者您已将其设置为分支表中不存在的数字。请将employees分支id设置为已存在的分支。如果不存在分支,请创建一个分支。只要员工正确引用分支机构,您就应该能够在代码中同时创建分支机构和员工。实体框架应首先保存分支,以便它在保存员工时存在其清除错误,即在保存员工对象时,分支未填充Monah,如果清除,他可能不会询问。。正如克里斯·塔兰特(Chris Tarrant)所说,“只有你知道答案,这才容易。”请忽略我之前的评论。谢谢你们,非常有帮助。我将为此付出一点努力,因为我实际上已经设置了分支id并填充了它,但至少我知道在哪里可以查看。再次感谢。考虑到是数据库出错,而不是EF出错,打开一些SQL EF运行的日志和运行时间可能会有所帮助;然后您可以看到导致错误的语句是什么。大约10秒钟后,您意识到EF正在试图保存“分支id-1的mr test employee”,您会突然想起您编写的测试/调试代码,100行(或类似的代码):)理解并非常有用,实际上我没有考虑日志选项:)。真的非常感谢。