EF5 code首先:强制多对多递归关系递归、关系、code

2023-09-06 17:11:52 作者:[ 命里从不缺狗 ]

我有一个简单的入门级车型

I have a simple Entry class model

public class Entry
{
    public int Id { get; set; }
    public DateTime Modified { get; set; }
    public DateTime Created { get; set; }

    // Related entries
    public virtual ICollection<Entry> RelatedEntries { get; set; }

    // The nodes this entry contains
    public virtual ICollection<Node> Nodes { get; set; }

    // The category this entry is located in
    public virtual Category Category { get; set; }
}

我想我的进入能够有相关的条目列表,问题是,它只是增加了一个FK Entry_id的条目表,我想创建一个新表,其中包含一个多对多的关系,例如

I want my entry to be able to have a list of related entries, the problem is it just adds a FK Entry_id to the Entries table, I want to create a new table, which holds a many to many relationship, for example

Entry_Id | Related_Entry_Id
      01 | 02
      01 | 03
      01 | 06
      02 | 04

这样就会使进入01相关的02,03和06,而进入02与04。

So that would make entry 01 related to 02, 03 and 06, and entry 02 with 04.

推荐答案

您可以用流利的API,我们的关系类型指定许多一对多(而不是一个一对多的关系,其中EF默认假定)

You can specify with Fluent API that the relationship is of type many-to-many (and not a one-to-many relationship which EF assumes by default):

public class MyContext : DbContext
{
    //...
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Entry>()
            .HasMany(e => e.RelatedEntries)
            .WithMany()
            .Map(m =>
            {
                m.MapLeftKey("Entry_Id");
                m.MapRightKey("Related_Entry_Id");
                m.ToTable("EntryRelations");
            });
    }
}