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

c# data-annotations entity-framework-core

Question

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?

1
0
2/1/2018 5:11:22 PM

Accepted Answer

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; }
}
1
2/1/2018 5:19:55 PM

Popular Answer

It's enough to set primary key attribute([Key]) in the OfficeAssignment class and in Instructor class we need to set such attribute:

[InverseProperty("Instructor")]

on collection of CourseAssignments. That will work as desired.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow