簡體   English   中英

如何在EF中使用共享外鍵

[英]How to work with Shared foreign key in EF

    [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

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


如果您僅需要共享主鍵關系,則使用上面的代碼沒有其他事情要做,因此請刪除注釋屬性。

您不能有兩個具有相同名稱的屬性。 嘗試這個:

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

順便說一句。 它看起來像一個非常奇怪的設計。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM