【问题标题】:Entity Framework Many-to-many relationships, with the same link entity实体框架多对多关系,具有相同的链接实体
【发布时间】:2013-04-19 17:23:47
【问题描述】:

我试图从一个包含多个实体之间的多对多关系数据的类中获得一些重用。

如果关系只是使用 Map 的两个实体的 pk,您可以很容易地做到这一点

class A{
   icollection<Item> Items
}    

class B{
   icollection<Item> Items
}

class Item{
   string Text
}

然后在配置中你做这样的事情

Entity<A>().HasMany(e=>e.Items).WithMany().Map(..);
Entity<B>().HasMany(e=>e.Items).WithMany().Map(..);

这会为 A 和 B 生成一个新的链接表

现在,我想在链接表上存储更多信息,但这很常见

class A{
   icollection<LinkItem> Items
}    

class B{
   icollection<LinkItem> Items
}

class LinkItem{
   int ExtraInfo
   Item Text
}

class Item{
   string Text
}

这会失败,因为 LinkItem 是在单个表中创建的并抱怨关系

“‘DataContext.LinkItem’中的实体参与‘A_Items’关系。找到0个相关的‘A_Items_Source’。预计有1个‘A_Items_Keywords_Source’。”

你可以在Map方法中指定一个表,m.ToTable("AItems"),但这也失败了

“模型中未找到指定的表'AItems'。请确保已正确指定表名。”

我可以以某种方式重用我的 LinkItem 类吗?

(不需要从DataContext中作为集合访问)

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    我相信你想要的可以做到,我刚刚尝试使用EF5,使用以下模型。

    public class UsersContext : DbContext
    {
        public DbSet<A> As { get; set; }
        public DbSet<B> Bs { get; set; }
        public DbSet<LinkItem> LinkItems { get; set; }
        public DbSet<Item> Items { get; set; }
    }
    
    public class A{
        public virtual int Id { get; set; }
        public virtual ICollection<LinkItem> Items { get; set; }
    }    
    
    public class B{
        public virtual int Id { get; set; }
        public virtual ICollection<LinkItem> Items { get; set; }
    }
    
    public class LinkItem{
        public virtual int Id { get; set; }
        public virtual DateTime ExtraInfo { get; set; }
        public virtual Item Text { get; set; }
    }
    
    public class Item{
        public virtual int Id { get; set; }
        public virtual string Text { get; set; }
    }
    

    这导致了以下数据库模型

    我没有添加任何自定义映射,只是使用了模型推断的内容。这对你有用吗?

    如果您想避免 LinkItems 表上的外键扩散,您可以使用以下 DbModelBuilder 命令将其与实体 A 和 B 建立多对多关系,这将添加隐式链接表。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<A>()
                    .HasMany(t => t.Items)
                    .WithMany();
        modelBuilder.Entity<B>()
                    .HasMany(t => t.Items)
                    .WithMany();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多