实体框架5 - 使用相同中间表的多个表之间的多对多关系

时间:2014-11-25 14:46:25

标签: entity-framework-5

我正在尝试使用Entity Framework 5实现以下场景,并采用代码优先方法。

情景:我有三张表说

Table1: { Id1, Title }

Table2: { Id2, Title }

Table3: { Id3, Title }

和单个中间表存储“Table1& Table2”和“Table2& Table3”之间的多对多关系。说,

TableIntermediate: { FK1,  FK2 }

要指定关系,On OnModelCreating(),我已指定了两个模型构建器:

modelBuilder.Entity<Table1>()
                 .HasMany(c => c.Table2s)
                 .WithMany(pc => pc.Table1s)
                 .Map(m =>
                 {
                     m.ToTable("TableIntermediate");
                     m.MapLeftKey("FK1");
                     m.MapRightKey("FK2");
                 });

 modelBuilder.Entity<Table1>()
                 .HasMany(c => c.Table3s)
                 .WithMany(pc => pc.Table1s)
                 .Map(m =>
                 {
                     m.ToTable("TableIntermediate");
                     m.MapLeftKey("FK1");
                     m.MapRightKey("FK2");
                 });

以下是定义的实体:

public class Table1
 {
  public int Id1 {get; set;}
  public string Title {get; set;}

  public ICollection<Table2> Table2s { get; set; }
  public ICollection<Table3> Table3s { get; set; }
 }

public class Table2
 {
  public int Id2 {get; set;}
  public string Title {get; set;}
  public ICollection<Table1> Table1s { get; set; }
 }

public class Table3
 {
  public int Id3 {get; set;}
  public string Title {get; set;}
  public ICollection<Table1> Table1s { get; set; }
 }

代码编译正确。但在运行时抛出错误:

  

{“指定的模式无效。错误:\ r \ n(275,6):错误0019:已经定义了具有模式”XXXX“和表”TableIntermediate“的EntitySet”Table1Table2“。每个EntitySet必须引用一个独特的架构和表格。“}

当我们使用现有数据库时,我们希望将这两个关系存储到一个中间表中。我找到的唯一解决方案是引入一个新的映射表。如果可以在不引入新映射表的情况下,请告诉我。

0 个答案:

没有答案