Foreign Key mapping to composite keys in entity framework

c# ef-code-first entity-framework

Question

Trying to setup the following relationship with entity framework code first. The following code does not work I've tried many variations... does anyone have a clue?

CONSTRAINT [FK_EVENT_Contact] FOREIGN KEY (Patient_ID,[Contact_ID]) REFERENCES
[PatientContact](Patient_ID,Person_ID)



public class PatientContact
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Person_ID { get; set; }
    public virtual Person Person { get; set; }

    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Patient_ID { get; set; }
    public virtual Patient Patient { get; set; }
}

public class Event
{
    [Key]
    public int Event_ID { get; set; }

    [Required]
    public int EventType_ID {get;set;}
    public virtual EventType EventType { get; set; }

    [ForeignKey("Patient")]
    public int Patient_ID { get; set; }
    public virtual Patient Patient { get; set; }

    [ForeignKey("PatientContact")]
    public int Contact_ID { get; set; }
    public virtual PatientContact PatientContact { get; set; }

}
1
8
12/27/2012 10:02:45 PM

Popular Answer

You have 2 options here.

Use attributes as you have eg:

[ForeignKey("PatientContact"), Column(Order = 0)]
public int Person_ID{ get; set; }
[ForeignKey("PatientContact"), Column(Order = 1)]
public int Patient_ID{ get; set; }
public virtual PatientContact PatientContact { get; set; }

Use the model builder (fluent api)

modelBuilder.Entity<Event>()
    .HasRequired(p => p.PatientContact)
    .WithMany()
    .HasForeignKey(p => new {p.Person_ID, p.Patient_ID});
18
12/27/2012 11:14:52 PM


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