EF5 code首先:强制多对多递归关系 [英] EF5 Code First: Force many to many recursive relationship

查看:635
本文介绍了EF5 code首先:强制多对多递归关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于EF5 code首先:强制多对多递归关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆