使用联结表和EF中的主键在同一个表上进行多对多关系

时间:2015-11-24 18:42:03

标签: entity-framework many-to-many primary-key

我有以下表格:

  • Private Sub ComboBox1_DropButtonClick() ' The following two lines avoid to call the routine twice, at entry and at exit Static i As Integer i = (i + 1) Mod 2: If i = 0 Then Exit Sub With ComboBox1 s = InputBox("enter some text", , .Value) '<~~ simulates any dialog If s <> "" Then .Value = s SendKeys ("{Enter}") '<~~ to close immediately the dropdown window End With End Sub Sub_Option为PK,Sub_Option_ID

  • NameSub_Option_To_Sub_Option为PK,Sub_Option_To_Sub_Option_IDSub_Option_ID_Primary

我希望能够通过EF访问与主要子选项关联的所有辅助子选项,反之亦然。直接使用Sub_Option_ID_Secondary不能正常工作,因为联结表.Map有一个主键。

Sub_Option_To_Sub_Option

对应表

public class Sub_Option
{
    public int Sub_Option_ID { get; set; }
    public string Name { get; set; }
}

和表

CREATE TABLE Sub_Option(
Sub_Option_ID int,
Name varchar(255)
);

1 个答案:

答案 0 :(得分:2)

我觉得这应该有效:

    public class OptionToOption
{
    [Key]
    public int ID { get; set; }

    [ForeignKey("PrimaryOption")]
    public int PrimaryID { get; set; }

    [ForeignKey("SecondaryOption")]
    public int SecondaryID { get; set; }

    public virtual Option PrimaryOption { get; set; }

    public virtual Option SecondaryOption { get; set; }
}

    public class Option
{
    public Option()
    {
        OptionToOption = new HashSet<OptionToOption>();
    }

    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<OptionToOption> OptionToOption { get; set; }
}

在这样流畅的api地图中(尽管不要认为这样做是必要的):

            modelBuilder.Entity<Option>()
            .HasMany(e => e.OptionToOption)
            .WithRequired(e => e.PrimaryOption)
            .HasForeignKey(e => e.PrimaryID);

        modelBuilder.Entity<Option>()
            .HasMany(e => e.OptionToOption)
            .WithRequired(e => e.SecondaryOption)
            .HasForeignKey(e => e.SecondaryID);