Search code examples
c#asp.net-core-mvcentity-framework-6

EF6 generates weird foreign keys


I am having a little problem using EF 6. These are my models (well, I am omitting the non-relevant properties):

[Table("Departments")]
public class Department
{
    public string Id { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }

    public IList<Staff> Staff { get; set; }

    public Staff HOD { get; set; }
}

[Table("Staff")]
public class Staff
{
    [Key]
    public string EmployeeId { get; set; }

    public string Name { get; set; }

    public Department Department { get; set; }
}

This is the migration that EF6 is generating (well, just the create methods):

CreateTable(
    "dbo.Staff",
    c => new
        {
            EmployeeId = c.String(nullable: false, maxLength: 128),
            Name = c.String(),
            Department_Id = c.String(maxLength: 128),
            Department_Id1 = c.String(maxLength: 128),
        })
    .PrimaryKey(t => t.EmployeeId)
    .ForeignKey("dbo.Departments", t => t.Department_Id)
    .ForeignKey("dbo.Departments", t => t.Department_Id1)
    .Index(t => t.Department_Id)      //what's this?
    .Index(t => t.Department_Id1);    //what's this?

CreateTable(
    "dbo.Departments",
    c => new
        {
            Id = c.String(nullable: false, maxLength: 128),
            Name = c.String(),
            Description = c.String(),
            HOD_EmployeeId = c.String(maxLength: 128),
        })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.Staff", t => t.HOD_EmployeeId)
    .Index(t => t.HOD_EmployeeId);

Take a look at the foreign keys generated. Something seems to be amiss. How do I correct this?


Solution

  • I had to use Fluent API to make this relationship work:

    modelBuilder.Entity<Staff>()
        .HasRequired<Department>(staff => staff.Department)
        .WithMany(department => department.Staff)
        .HasForeignKey<string>(staff => staff.DepartmentId);
    

    Changes to the models:

    public Department Department { get; set; }
    

    changed to

    public string DepartmentId { get; set; }
    public virtual Department Department { get; set; }
    

    and

    public IList<Staff> Staff { get; set; }
    
    public Staff HOD { get; set; }
    

    changed to

    public virtual IList<Staff> Staff { get; set; }
    
    public Staff HOD { get; set; }