0

I have the following classes

public class Employee
{ 
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }
    public string PhoneNumber { get; set; }
    public Guid DepartmentId { get; set; }
    public virtual Department Department { get; set; }
    public int Deleted { get; set; }

    public bool IsDeleted()
    {
        return this.Deleted == 1 ? true : false;
    }

    public void MarkAsDeleted()
    {
        this.Deleted = 1;
    }

    public string GetFullName()
    {
        return this.FirstName + " " + this.LastName;
    }
}

public class Department
{
    public Department()
    {
        this.Employees = new List<Employee>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual List<Employee> Employees { get; set; }
    public int Deleted { get; set; }

    public bool IsDeleted()
    {
        return this.Deleted == 1 ? true : false;
    }

    public void MarkAsDeleted()
    {
        this.Deleted = 1;
    }

    public void AddEmployee(Employee employee)
    {
        this.Employees.Add(employee);
    }

    public void RemoveEmployee(Employee employee)
    {
        this.Employees.Remove(employee);
    }
}

And I want to create a one-to-many relationship and in my configuration I have the following code for this

 [modelBuilder.Entity<Department>()
            .HasMany(l => l.Employees).
               WithRequired(r => r.Department).
               HasForeignKey(r => r.DepartmentId);

But it throws an exception

The INSERT statement conflicted with the FOREIGN KEY constraint \FK_dbo.Employees_dbo.Departments_DepartmentId. The conflict occurred in database \Entities\, table \dbo.Departments\, column Id

Can anyone please help me? Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
joesid
  • 671
  • 1
  • 10
  • 21

1 Answers1

4

It seems that at some point you are trying to save an Employee without a
Department. Therefore the relationship is failing.

J. Pichardo
  • 3,077
  • 21
  • 37