Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

c# - Foreign Key mapping to composite keys in entity framework

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...