Getting error while inserting department foreign key in Employee table

entity-framework entity-framework-6

Question

I am beginner to Entity Framework. I want to insert employees along with department as foreign key, but I am getting the following error while adding records:

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.

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

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

Index action:

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
2/24/2019 6:16:07 AM

Accepted Answer

Usually this error thrown when you are assigning a value to the ForeignKey but there is no such data with that value in ForeignKey table.

In your case there is no Department with Id = 2 in your Department table . So you can check it in your Departement table.

1
2/24/2019 4:35:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow