在 Employee table 中插入部门外键时出错

Getting error while inserting department foreign key in Employee table

我是 Entity Framework 的初学者。我想插入员工和部门作为外键,但在添加记录时出现以下错误:

The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Employees_dbo.Departments_DepartmentId\". The conflict occurred in database \"EmpDB\", table \"dbo.Departments\", column 'Id'.\r\nThe statement has been terminated.

部门 class:

namespace DbSet_Exmp.Models
{
    public class Department
    {
        public int Id { get; set; }
        public string DeptName { get; set; }
        public virtual ICollection<Employee> Employees { get; set; }
    }
}

员工 class:

namespace DbSet_Exmp.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Contact { get; set; }
        public int Salary { get; set; }
        public int DepartmentId { get; set; }
        public virtual Department Department { get; set; }
    }
}

DbContext class:

public class EmpDbContext:DbContext
{
    public EmpDbContext() : base("name=myDBConString")
    {
        Database.SetInitializer(new DBInitializer());
    }

    public DbSet<Department> Departments { get; set; }
    public DbSet<Employee> employees { get; set; }
}

索引 动作:

public ActionResult Index()
{            
    using (var context = new EmpDbContext())
    {
         Employee objEmp = new Employee() { Name = "Swara", Contact = "123569", Salary = 15000, DepartmentId = 2 };
         context.employees.Add(objEmp);
         context.SaveChanges();               
    }

    return View();
}

通常当您为 ForeignKey 赋值时抛出此错误,但在 ForeignKey table.

中没有具有该值的此类数据

在您的情况下,Department table 中没有 DepartmentId = 2。所以你可以在你的 Departement table.

中检查它