在雇员表中插入部门外键时出错



我是实体框架的初学者。我想将员工与部门一起作为外键插入,但在添加记录时出现以下错误:

INSERT 语句与外键约束 \"FK_dbo 冲突。Employees_dbo。Departments_DepartmentId\"。冲突发生在数据库 \"EmpDB\", 表 \"dbo 中。部门",列"Id"。\r语句已终止。

部门类:

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

员工类别:

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类:

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此类数据时,会引发此错误。

在您的情况下,您的Department表中没有Id = 2Department。因此,您可以在Departement表中检查它。

最新更新