Search code examples
c#entity-framework-coredata-annotations

Can't set primary key and foreign key on one column


So I try to create some ASP.NET project with EF Core.

I want to set propert of one entity as primary key and foreign key to another entity. The relationship is 0..1 - 1. I use DataAnnotations:

public class OfficeAssignment
{
    [Key, ForeignKey("InstructorID")]
    public int InstructorID { get; set; }
    public Instructor Instructor { get; set; }
    public string Location { get; set; }
}

But I keep getting column InstructorID as PK and InstructorID1 as FK... Any ideas, why EF behaves like that and how can I achieve my goal?


Solution

  • You should follow convention over configuration as much as you can. An OfficeAssignment entity should have an OfficeAssignmentId PK, like this:

    public class OfficeAssignment
    {
        public int OfficeAssignmentId { get; set; }
    
        //Notice that Id does not have an uppercase D
        public int InstructorId { get; set; }
        public string Location { get; set; }
    
        public Instructor Instructor { get; set; }
    }
    

    However, if you don't want to follow normal conventions, the name of the property that goes in the ForeignKey attribute is the opposite of where it's declared:

    public class OfficeAssignment
    {
        [Key, ForeignKey("Instructor")]
        public int InstructorId { get; set; }
        public string Location { get; set; }
    
        public Instructor Instructor { get; set; }
    }
    

    And, if you want to keep it compile-time safe:

    public class OfficeAssignment
    {
        [Key, ForeignKey(nameof(Instructor))]
        public int InstructorId { get; set; }
        public string Location { get; set; }
    
        public Instructor Instructor { get; set; }
    }