在“员工”表中插入部门外键时出现错误

时间:2019-02-24 03:18:47

标签: entity-framework entity-framework-6

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

  

INSERT语句与FOREIGN KEY约束\“ FK_dbo.Employees_dbo.Departments_DepartmentId \”冲突。数据库\“ EmpDB \”,表\“ dbo.Departments \”,列'Id'中发生冲突。\ r \ n该语句已终止。

部门课程:

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

1 个答案:

答案 0 :(得分:1)

通常,在为ForeignKey分配值时抛出此错误,但是ForeignKey表中没有具有该值的此类数据。

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