Così provo a creare un progetto ASP.NET con EF Core.
Voglio impostare propert di un'entità come chiave primaria e chiave esterna per un'altra entità. La relazione è 0..1 - 1
. Io uso DataAnnotations
:
public class OfficeAssignment
{
[Key, ForeignKey("InstructorID")]
public int InstructorID { get; set; }
public Instructor Instructor { get; set; }
public string Location { get; set; }
}
Ma continuo a ricevere InstructorID
come PK e InstructorID1
come FK ... Qualche idea, perché EF si comporta così e come posso raggiungere il mio obiettivo?
Dovresti seguire la convenzione sulla configurazione il più possibile. Un'entità OfficeAssignment
deve avere un PK OfficeAssignmentId
, come questo:
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; }
}
Tuttavia, se non si desidera seguire le normali convenzioni, il nome della proprietà che va nell'attributo ForeignKey
è l'opposto di dove è dichiarato:
public class OfficeAssignment
{
[Key, ForeignKey("Instructor")]
public int InstructorId { get; set; }
public string Location { get; set; }
public Instructor Instructor { get; set; }
}
E, se vuoi mantenerlo al sicuro in fase di compilazione:
public class OfficeAssignment
{
[Key, ForeignKey(nameof(Instructor))]
public int InstructorId { get; set; }
public string Location { get; set; }
public Instructor Instructor { get; set; }
}
È sufficiente impostare l'attributo della chiave primaria ( [Key]
) nella classe OfficeAssignment
e nella classe Instructor
dobbiamo impostare tale attributo:
[InverseProperty("Instructor")]
alla raccolta di CourseAssignments
. Funzionerà come desiderato.