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

c# data-annotations entity-framework-core

Accepted Answer

Convention should always be preferred over configuration whenever possible. AnOfficeAssignment entity need to own anOfficeAssignmentId Like this, PK

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; }
}

But if you wish to deviate from accepted practices, the name of the property that appears in theForeignKey The opposite of where it is stated is attribute:

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

    public Instructor Instructor { get; set; }
}

Additionally, to make it secure at compilation time:

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

ZZZ_tmp


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