How to establish 1:1 relationship with 2 composite keys in EF6 (not core)

22 Views Asked by At

I have been reading docs and lots of posts, but have not found a way to make this work, yet. Entity Framework 6 on a .Net Framework 4.7.2 app.

Db (I cannot alter this):

// Parent table name: 'Parents'
  ParentId (PK, int, not null)
  ArchtypeId (PK, FK, int, not null)
  MiscParentData (varchar(666), not null)

// Child table name: 'ChildData'
  ChildId (PK, int, not null)
  ArchtypeId (PK, FK, int, not null)
  ParentId (FK, int, not null)
  MiscChildData (varchar(666), not null)

Example models:

public class Parent
{
        [Key, Column(Order = 1)]
        public int ArchtypeId{ get; set; }

        [Key, Column(Order = 2)]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ParentId { get; set; }

        [ForeignKey("ArchtypeId,ParentId")]
        public Child Child { get; set; } 

        public string MiscParentData { get; set; }
}

[Table("ChildData")] // I cannot alter the db table name
public class Child
{ 
        [Key, Column(Order = 1)]
        public int ArchtypeId{ get; set; }

        [Key, Column(Order = 2)]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ChildId { get; set; }

        public string MiscChildData { get; set; }
}

Exception synopsis:

System.InvalidOperationException: 
Unable to determine the principal end of an association between the types 'Child' and 'Parent'. 
The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

I have tried a lot of different things and the above seems like it should have everything covered. Any advice or maybe old applicable docs would be appreciated! Could this be a Db column config problem?

0

There are 0 best solutions below