The INSERT statement conflicted with the FOREIGN KEY constraint for code first Entity Framework

773 Views Asked by At

System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.employee_entity_dbo.person_entity_id". The conflict occurred in database "EFEmployeeEntityModelContext", table "dbo.person_entity", column 'id'.

So I'm getting this error when I'm trying to insert an employee entity and I'm not sure why. I also have a person entity class which has a one to zero-or-one relationship with the employee entity. So each employee is a person, but each person is not necessarily an employee. To make this relationship, in my employee entity class I have a property which is PersonID. So this PersonID is supposed to be the foreign key which relates to the Id primary key of the person entity. Here is my employee entity class:

[Table("employee_entity")]
public class EFEmployee : EFBusinessEntity
{
    [Column("office_id")]
    public Guid OfficeID { get; set; }

    [Column("person_id")]
    //[Index("ix_employee_person_id", IsUnique=true)]
    public Guid PersonID { get; set; }

    [Column("hire_date")]
    public DateTime HireDate { get; set; }

    [Column("job_title")]
    [Required]
    public byte[] JobTitle { get; set; }

    [Column("salary")]
    public int Salary { get; set; }

    [Column("certifications")]
    public byte[] Certifications { get; set; }

    [Column("vacation_time")]
    public int VacationTime { get; set; }

    [Column("sick_time")]
    public int SickTime { get; set; }

    public virtual EFOffice Office { get; set; }

    public virtual EFPerson Identity { get; set; }

    public virtual EFEmployee ReportingTo { get; set; }

    public EFEmployee(Guid id, Guid tenantId, Guid officeID, Guid personID, DateTime hire, byte[] titles, int salary, byte[] certifications, int vacationTime, int sickTime)
    {
        this.Id = id;
        this.TenantId = tenantId;
        this.OfficeID = officeID;
        this.PersonID = personID;
        this.HireDate = hire;
        this.JobTitle = titles;
        this.Salary = salary;
        this.Certifications = certifications;
        this.SickTime = sickTime;
        this.VacationTime = vacationTime;
    }
}

Here is the class for the Person entity:

[Table("person_entity")]
public class EFPerson : EFBusinessEntity
{
    [Column("first_name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Column("last_name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Column("phone_num")]
    public uint? PhoneNum { get; set; }

    [Column("date_of_birth")]
    public DateTime DateOfBirth { get; set; }

    public virtual EFEmployee Employee { get; set; }

    public EFPerson(Guid id, Guid tenantId, string firstName, string lastName, DateTime dob)
    {
        this.Id = id;
        this.TenantId = tenantId;
        this.FirstName = firstName;
        this.LastName = lastName;
        this.DateOfBirth = dob;
    }
}

Here is the base entity class:

[Table("business_entity")]
public abstract class EFBusinessEntity : IBusinessEntity
{
    [Column("tenant_id")]
    public Guid TenantId
    {
        get;
        set;
    }

    [Column("id")]
    [Key]
    public Guid Id
    {
        get;
        set;      
    }
}

Here is the test case I'm running which gives me the error for inserting an employee:

public void TestInsertEmployee1()
{
    InitializeDatabase();

    EFEmployee testEmployee = InitializeEmployee1();
    EFRepo.Insert<EFEmployee>(testEmployee);

    EFEmployee randomEmployee = EFRepo.GetById<EFEmployee>(testEmployee.Id);
    Debug.Assert(testEmployee.Equals(randomEmployee));
}

InitializeEmployee1() creates a test employee, and when I initialize it I make sure it uses the same PersonID as I do when I call InitializePerson1(). I make sure of this by calling

Debug.WriteLine(testEmployee.PersonID);

And then I compare this to the Id of Person in the person_entity table in Microsoft SQL Server. If the two IDs match up, then what's the problem?

Also I use fluent API to do the mapping in the OnModelCreating method of the database context class:

modelBuilder.Entity<EFEmployee>().HasRequired(t => t.Office).WithMany(u => u.Employees).HasForeignKey(d => d.OfficeID);

modelBuilder.Entity<EFEmployee>().HasRequired(t => t.Identity).WithOptional(u => u.Employee);
0

There are 0 best solutions below