【问题标题】:How to work with Shared foreign key in EF如何在 EF 中使用共享外键
【发布时间】:2012-04-23 09:38:22
【问题描述】:
    [Table("Table1")]
    public class Entity1
    {
       [Key, ForeignKey("entity1")]
       public int ID{get;set;}
       public virtual Entity2 entity2{get;set;}
       public virtual Entity3 entity3{get;set;}
    }


这是我的主要实体。在这里,我想将此实体与 Entity2 和 3 映射为具有相同的外键,该外键也是 Entity1,2,3 中的主键。

    [Table("Table2")]
    public class Entity2
    {
       [Key]
       public int Entity1ID{get;set;}
       // few entity specific properties
    }


    [Table("Table3")]
    public class Entity3
    {
       [Key]
       public int Entity1ID{get;set;}
       // few entity specific properties
    }


什么时候使用我的上下文类进行映射,然后我收到一条错误消息:the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must

【问题讨论】:

    标签: asp.net asp.net-mvc-3 entity-framework ef-code-first


    【解决方案1】:
    modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2)
                               .WithRequired();
            modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2)
                              .WithRequired();
    


    如果你只需要共享主键关系,那么使用上面的代码就没什么多余的了,所以去掉注解属性。

    【讨论】:

      【解决方案2】:

      您不能拥有两个同名的属性。试试这个:

      [Table("Table1")]
      public class Entity1
      {
         [Key, ForeignKey("Entity2"), ForeignKey("Entity3")]
         pubic int ID{get;set;}
         public virtual Entity2 Entity2{get;set;}
         public virtual Entity3 Entity3{get;set;}
      }
      

      顺便说一句。看起来很奇怪的设计。

      【讨论】:

      • 错误:外键属性重复
      • 在这种情况下尝试使用 Fluent API 而不是属性。
      • 在这里建议我可能的解决方案。
      猜你喜欢
      • 1970-01-01
      • 2012-11-18
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      • 2022-01-23
      • 2014-02-26
      相关资源
      最近更新 更多