【问题标题】:class that represents an item with attributes where attributes are in a collection of attribute objects, using code first migrations表示具有属性的项目的类,其中属性位于属性对象的集合中,使用代码优先迁移
【发布时间】:2014-04-28 17:27:43
【问题描述】:

我正在尝试做一个由两个类/表组成的代码优先实体框架项目。 一个类代表一个小部件。第二个类/表包含这个小部件的属性。即右螺纹、左螺纹、小、大等。

每个 Widget 可以有 1 个或多个属性,每个属性可以属于多个小部件。

我首先在代码中应该如何表示这一点。

    class Widget{
      public int Id {get;set;}
      public string Name {get;set;}
      public ICollection<Attribute> Attributes{get; set;}
    }

    class Attribute{
      public int Id{ get; set;}
      public string Name{get; set;}
    }

上面的类给了我两个表和数据库中相同属性的多个副本。

最终我试图将属性表用作可扩展的枚举类型。

【问题讨论】:

  • 我想我需要添加一个中间表。即 WidgetAttributes

标签: entity-framework c#-4.0 ef-code-first entity-framework-5


【解决方案1】:

因为您在 Attribute 实体上没有导航属性,所以实体框架不会按照约定确定存在多对多关系。它将改为创建一对多。要指定多对多关系,需要在上下文中添加映射代码。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Widget>()
        .HasMany(w => w.Attributes)
        .WithMany();
}

您链接的示例中的 .Map() 代码仅在您希望指定列名或表名时才需要。如果您省略该代码,实体框架将提供名称。

【讨论】:

    【解决方案2】:

    我最终找到了一篇解释得很好的相关文章。我担心文章的年代以及自 2011 年以来是否有任何变化。 Many to Many article

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多