简体   繁体   中英

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


This is my main Entity. Here I want to map this Entity with Entity2 and 3 with the same foreign key which is also primary key in 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
    }


When is use my context class for mapping then i receive an error says 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();


If you need Shared primary key relationship only , then use the code above there is nothing extra to do, so remove annotation attributes.

You cannot have two properties with the same name. Try this:

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

Btw. it looks like a very strange design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM