实体框架错误消息DbUpdateException

时间:2017-11-26 12:01:01

标签: c# database entity-framework-6

作为作业的一部分,我必须使用Entity Framework创建一个Web应用程序。我正在https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application关注教程。

共有四个表:BranchDepartmentEmployeeTitle

创建种子数据的方法后,我已在调试模式下运行应用程序,并收到以下错误消息:

  

System.Data.Entity.Infrastructure.DbUpdateException:'更新条目时发生错误。有关详细信息,请参阅内部异常。'SqlException:INSERT语句与FOREIGN KEY约束“FK_dbo.Employee_dbo.Branch_BranchId”冲突。冲突发生在数据库“HumanResourcesWebApp1”,表“dbo.Branch”,列“ID”中。声明已经终止。

我已经研究过这条消息,但我没有按照我发现的答案。我会感激一些方向。我也在添加类的结构,如果它有帮助。我理解问题是Branch表的主键在Employee表被视为外键时,但我不知道在哪里进行更改。

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

提前致谢

1 个答案:

答案 0 :(得分:1)

您尝试保存引用不存在的分支的员工详细信息。这可能是因为您根本没有设置分支ID,或者您已将其设置为分支表中不存在的数字将employees分支ID设置为已存在的分支。如果不存在分支,则创建一个分支。只要员工正确引用分支,您就应该能够在代码中同时创建分支和员工。实体框架应首先保存分支,以便它在保存员工

时存在
相关问题