【问题标题】:Foreign Key mapping to composite keys in entity framework外键映射到实体框架中的复合键
【发布时间】:2012-12-27 18:14:33
【问题描述】:

首先尝试与实体框架代码建立以下关系。以下代码不起作用我尝试了很多变体...有人有线索吗?

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

}

【问题讨论】:

  • 欢迎来到 Stack Overflow!你遇到了什么错误?你到底想完成什么?

标签: c# entity-framework ef-code-first


【解决方案1】:

这里有 2 个选项。

使用属性,例如:

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

使用模型构建器(fluent api)

modelBuilder.Entity<Event>()
    .HasRequired(p => p.PatientContact)
    .WithMany()
    .HasForeignKey(p => new {p.Person_ID, p.Patient_ID});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    相关资源
    最近更新 更多