如何在EF中使用共享外键

时间:2012-04-23 09:38:23

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

    [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;}
    }

这是我的主要实体。在这里,我想使用相同的外键映射此Entity与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

2 个答案:

答案 0 :(得分:2)

modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2)
                           .WithRequired();
        modelBuilder.Entity<Entity1>().HasOptional(u => u.Entity2)
                          .WithRequired();


如果您只需要共享主键关系,那么使用上面的代码没有什么额外的事情要做,所以删除注释属性。

答案 1 :(得分:-1)

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

[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;}
}

顺便说一下。它看起来像一个非常奇怪的设计。