EF5 Code First: Force many to many recursive relationship

浪尽此生 提交于 2019-12-11 08:29:58

问题


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

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

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


回答1:


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


来源:https://stackoverflow.com/questions/12252868/ef5-code-first-force-many-to-many-recursive-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!