【问题标题】:Entity Framework6 2 * many-to-many to selfEntity Framework6 2 * 多对多到自己
【发布时间】:2018-12-06 12:42:58
【问题描述】:

在 Entity Framework 6 中使用代码优先。

我有这个实体:

public class LineSection
{
    public int Id { get; set; }
    public List<LineSection> Next { get; set; }
    public List<LineSection> Previous { get; set; }
}

我添加一个迁移,只是为了看看数据库将如何:

        CreateTable(
            "dbo.LineSectionLineSections",
            c => new
                {
                    LineSection_Id = c.Int(nullable: false),
                    LineSection_Id1 = c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.LineSection_Id, t.LineSection_Id1 })
            .ForeignKey("dbo.LineSections", t => t.LineSection_Id)
            .ForeignKey("dbo.LineSections", t => t.LineSection_Id1)
            .Index(t => t.LineSection_Id)
            .Index(t => t.LineSection_Id1);

我不喜欢默认命名。我可以更改表名(LineSectionLineSections)和两个外键(LineSection_Id 和 LineSection_Id1)。使用模型构建器、数据属性或其他方式?

【问题讨论】:

  • MapLeftKey, MapRightKey。例子很多,比如stackoverflow.com/questions/16490334/…
  • 请为我的案例展示一个完整的例子。据我所知,您的示例不适合我的情况,因为实体中只有列表,而不是两个。
  • 没关系,但你去吧。

标签: entity-framework entity-framework-6 ef-code-first


【解决方案1】:

使用Mapfluent API 进行隐式连接表的多对多关系配置(t 是否为self 无关)。可以使用ToTable指定表名,MapLeftKey/MapRightKey指定对应的列名(左边是正在配置的实体,右边是关系的另一端)。

所以在你的情况下,它会是这样的:

modelBuilder.Entity<LineSection>()
   .HasMany(e => e.Next)
   .WithMany(e => e.Previous)
   .Map(m => m.MapLeftKey("PrevId")
          .MapRightKey("NextId")
          .ToTable("LineSectionLinks")
   );

【讨论】:

  • 老实说我不明白,但它很好用:-)
猜你喜欢
  • 1970-01-01
  • 2010-09-14
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 2018-11-07
  • 2011-07-20
  • 2021-02-08
相关资源
最近更新 更多