I am trying to define these tables.
_tbl1_
id (PK)
_tbl2_
id (PK)
tbl1_id (FK)
_tbl3_
id (PK)
tbl1_id (FK)
...where I can navigate from Tbl1 to Tbl2 or Tbl3
or back from Tbl2 or Tbl3 to Tbl1.
While the association from Tbl2 or Tbl3 to Tbl1 are required, a record in Tbl2 or Tbl3 may not exist; so Tbl1 records should be able to exist with our both or one of Tbl2 and Tbl3.
The design is this way to have optional relationships to two completely different entities from the perspective of Tbl1.
class Tbl1
{
[Key]
public int Id { get; set; }
public Tbl2 Tbl2 { get; set; }
public Tbl2 Tbl3 { get; set; }
}
class Tbl2
{
[Key]
public int Id { get; set; }
[ForeignKey("Tbl1")]
public int Tbl1Id { get; set; }
public Tbl1 Tbl1 { get; set; }
}
class Tbl3
{
[Key]
public int Id { get; set; }
[ForeignKey("Tbl1")]
public int Tbl1Id { get; set; }
public Tbl1 Tbl1 { get; set; }
}
and fluent...
modelBuilder.Entity<Tbl2>()
.HasRequired(e => e.Tbl1)
.WithOptional(e => e.Tbl2);
modelBuilder.Entity<Tbl3>()
.HasRequired(e => e.Tbl1)
.WithOptional(e => e.Tbl3);
Using the above I get an error of:
Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
Which seems to imply that the foreign key must be the record key as well.
So, can I do this? Can I not?.
I am happy to implement with either attributes or fluent api or both.