efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Composite Foreign Key exception

Open lukgit17 opened this issue 9 years ago • 6 comments

Exception System.InvalidOperationException: The entity type 'Table_A' requires a primary key to be defined appear when query Table_B. I Have Table_A defined in Schema A with composite primary key :

builder.Entity<Table_A>()
    .HasKey(l=>new {l.Column1,l.Column2}) , 

and in Schema B I have defined Table_B with composite primary key and One-to-One relation with composite foreign key :

builder.Entity<Table_B>()
    .HasKey(dl=> new{dl.Column1,dl.Column2});         

builder.Entity<Table_B>()
    .HasOne(dl=>dl.Table_A)
    .WithOne(l=>l.Table_B)
    .HasForeignKey<Table_A>(l=>new {l.Column1,l.Column2});

In model Table_A is defined property Table_B Table_B { get; set; }, and in model Table_B is defined property Table_A Table_A { get; set; }

Further technical details

EF Core version: 2.0.0 Database Provider: Mysql Operating system: Windows 10 IDE: Visual Studio Code

lukgit17 avatar Sep 25 '17 05:09 lukgit17

Temporary workaround is to rename only Column1 as id. This issue will be solved in next version? Is not ok to be required that composite primary key contain first column named id.

lukgit17 avatar Sep 25 '17 11:09 lukgit17

@lukgit17 Extrapolating from the snippets above I created these entity types and configuration:

public class Table_A
{
    public int Column1 { get; set; }
    public int Column2 { get; set; }
    public Table_B Table_B { get; set; }
}

public class Table_B
{
    public int Column1 { get; set; }
    public int Column2 { get; set; }
    public Table_A Table_A { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Table_A>()
        .HasKey(l => new { l.Column1, l.Column2 });
    
    modelBuilder.Entity<Table_B>()
        .HasKey(dl => new { dl.Column1, dl.Column2 });

    modelBuilder.Entity<Table_B>()
        .HasOne(dl => dl.Table_A)
        .WithOne(l => l.Table_B)
        .HasForeignKey<Table_A>(l => new { l.Column1, l.Column2 });
}

This did not result in any exception and the resulting model looks correct:

Model: 
  EntityType: Table_A
    Properties: 
      Column1 (int) Required PK FK AfterSave:Throw 0 0 0 -1 -1
      Column2 (int) Required PK FK AfterSave:Throw 1 1 1 -1 -1
    Navigations: 
      Table_B (<Table_B>k__BackingField, Table_B) ToPrincipal Table_B Inverse: Table_A 0 -1 2 -1 -1
    Keys: 
      Column1, Column2 PK
    Foreign keys: 
      Table_A {'Column1', 'Column2'} -> Table_B {'Column1', 'Column2'} Unique ToDependent: Table_A ToPrincipal: Table_B
  EntityType: Table_B
    Properties: 
      Column1 (int) Required PK AfterSave:Throw 0 0 0 -1 -1
      Column2 (int) Required PK AfterSave:Throw 1 1 1 -1 -1
    Navigations: 
      Table_A (<Table_A>k__BackingField, Table_A) ToDependent Table_A Inverse: Table_B 0 -1 2 -1 -1
    Keys: 
      Column1, Column2 PK

Could you look at the code above and see what needs to be changed to reproduce the behavior you are seeing?

ajcvickers avatar Sep 25 '17 20:09 ajcvickers

I was mentioned that tables is in different contexts : Table_A is in Schema_A (DB_Context_A) and Table_B is in Schema_B (DB_Context_B). In same context i have tables with composite foreign in primary keys which working.

lukgit17 avatar Sep 26 '17 05:09 lukgit17

@lukgit17 Still works for me when I add .ToTable("Table_A", "Schema_A"); and .ToTable("Table_B", "Schema_B");

Can you explain more about what you mean by "different contexts"?

ajcvickers avatar Sep 26 '17 16:09 ajcvickers

I say that Table_A is in DB_CONTEXT_A class and Table_B in different DB_CONTEXT_B class. I put real example from code next :

  • DB Context Classes, each for schema
public class CommonContext : DbContext
    {
        public CommonContext(DbContextOptions<CommonContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder builder)
        {            
            builder.HasDefaultSchema("common_saf");

            builder.Entity<Lot>().HasKey(l=>new {l.numarLot,l.idCategorieProdus});
            builder.Entity<Lot>().HasOne(l => l.detaliiLot).WithOne(dl =>       dl.lot).HasForeignKey<DetaliiLoturiZi>(l=>new{l.numarLot,l.idCategorieProdus});

            base.OnModelCreating(builder);
       }
    }
public class ComenziContext : DbContext
    {
        public ComenziContext(DbContextOptions<ComenziContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.HasDefaultSchema("comenzi");

            builder.Entity<DetaliiLoturiZi>().HasKey(dl=> new{dl.numarLot,dl.idCategorieProdus});         
            builder.Entity<DetaliiLoturiZi>().HasOne(dl=>dl.lot).WithOne(l=>l.detaliiLot).HasForeignKey<Lot>(l=>new {l.numarLot,l.idCategorieProdus});

             base.OnModelCreating(builder);
         }
     }


  • models
[TableAttribute("loturi",Schema="common_saf")]
    public class Lot
    {
        [Required,Column("numar_lot")]
        public int numarLot { get; set; }
        [Required,Column("data_lot")]        
        public DateTime dataLot { get; set; }
        [Required,Column("detalii")]        
        public string detalii { get; set; }        
        [Required,Column("id_ferma")]
        public int idFerma { get; set; } 
        [ForeignKey("idFerma")]
        public Ferma ferma { get; set; }                      
        [Column("id_brand")]
        public int idBrand { get; set; }          
        [ForeignKey("idBrand")]
        public BrandProdus brandProdus { get; set; }             
        [Required,Column("id_categorie_produs")]
        public int idCategorieProdus { get; set; }                  
        [ForeignKey("idCategorieProdus")]
        public GrupaProdus categorieProdus { get; set; }             

        public DetaliiLoturiZi detaliiLot { get; set; }
    }
[TableAttribute("detalii_loturi_zi",Schema="comenzi")]
    public class DetaliiLoturiZi
    {
        [Required,Column("lot")]
        public int numarLot { get; set; } 
        [Required,Column("id_categorie_produs")]
        public int idCategorieProdus { get; set; }                       
        [Required,Column("data")]
        public DateTime data { get; set; }
        [Required,Column("greutate")]
        public double greutate { get; set; }       

        public Lot lot { get; set; }          
    }

lukgit17 avatar Sep 27 '17 05:09 lukgit17

@lukgit17 Each context needs to have a fully-defined, self-contained model. If both entity types are going to be used by both contexts--which is true if there are relationships between the types--then both entity types need to be configured in both models.

ajcvickers avatar Sep 27 '17 16:09 ajcvickers