Sandeep
Sandeep

Reputation: 21

Getting error while inserting department foreign key in Employee table

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

Upvotes: 0

Views: 198

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32059

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.

Upvotes: 1

Related Questions