【问题标题】:Code first entities don't relate in database代码优先实体在数据库中不相关
【发布时间】:2012-08-01 11:56:08
【问题描述】:

我是 Code First 的新手,并尝试构建我的数据模型。 一切都很好,除了一个问题,我尝试映射接下来的事情:

public class Something
{
       ...
       public virtual Layer Layer1 { get; set; }
       public virtual Layer Layer2 { get; set; }
       public virtual Layer Layer3 { get; set; }
       ...
}

public class Layer
{
       ...
       public virtual Something Something { get; set; }
       ...
}

Something 类映射正常,但是从 Layer 到S​​omething 的关系根本不映射,在数据库表中有null,我几乎尝试了所有东西,现在我不知道...... 为什么Layer不能引用Something?

提前致谢。

【问题讨论】:

  • 数据库表中的实际内容是null 还是Something 属性是null? EF 仅在某些情况下同步导航属性(例如,当调用 SaveChanges 时)。
  • SaveChanges() 之后什么都没有。只是空字段。
  • 您是否在 DbContext 中同时引用了 LayerSomething?表格是否正确创建?
  • 是的。这两个表都在 DbContext 中。有些东西正确地与图层相关,但仅以这种方式。
  • 你能分享你剩下的Something和Layer模型吗?他们有 Id 属性吗?

标签: c# ef-code-first entity-framework-4.3


【解决方案1】:
  1. 你有三个FK,所以你需要Something类中的三个Layer类型的属性,以及Layer类中Something类型的三个属性。您无法以某种方式将 Layer 类中所有相关的Something 收集到一个属性中。
  2. 由于两个表之间有多个 FK,因此您需要指定 id,并使用数据注释将 id 与导航属性连接起来。
  3. 我假设'正常' FK's,这意味着层记录可以被多个Something's 引用。如果是这种情况,那么 Layer 类中的 Something-properties 就需要是集合。

综合起来,结果是:

public class Something {
        public int SomethingId { get; set; }
        [ForeignKey("Layer1")]
        public int Layer1Id { get; set; }
        [ForeignKey("Layer2")]
        public int Layer2Id { get; set; }
        [ForeignKey("Layer3")]
        public int Layer3Id { get; set; }
        [ForeignKey("Layer1Id")]
        public Layer Layer1 { get; set; }
        [ForeignKey("Layer2Id")]
        public Layer Layer2 { get; set; }
        [ForeignKey("Layer3Id")]
        public Layer Layer3 { get; set; }
    }

    public class Layer {
        public int LayerId { get; set; }
        [InverseProperty("Layer1")]
        public Something Something1 { get; set; }
        [InverseProperty("Layer2")]
        public Something Something2 { get; set; }
        [InverseProperty("Layer3")]
        public Something Something3 { get; set; }
    }

【讨论】:

  • 谢谢,Layer 必须只有一个 Something。我所需要的只是从我的图层中访问某物。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 2012-05-09
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
相关资源
最近更新 更多