Adding custom navigation property in Entity Framework Core for table that does not have an explicit foreign key

.net-core c# entity-framework-core sql-server

Question

I have 2 separate models that logically are one-to-many but there is no explicit foreign key relationship.

Table1 has a one-to-many with Table2

The models are as follows:

public class Table1
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
}

public class Table2
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}
    public string RelatedTableName {get; set;}
    public string? RelatedTableId {get; set;}
}

Table2 would, for the time being, have "Table1" and "10" as the RelatedTableName and RelatedTableId respectively. In the future, there could potentially be a Table3 that also has a one-to-many with Table2 in the same way.

Is there any way, using fluent API or anything else, that would allow EF to understand this relationship?

The reason I'm asking is because a record in Table1 is created at the same time as the records in Table2. Normally, to associate these records, you would add them to each other's navigation properties as Table1's Id has not yet been generated. In this example, it does not seem so straightforward to do that.

There is another workaround that I can take - saving the first entity before the second. I'd prefer not to do this.

1
0
4/3/2020 4:33:50 AM

Popular Answer

EF is essentially a mapping between your C# model and the DB Schema. What you have asked for cannot be done in the Database (a single column that can be a foreign key for multiple tables). If the underlying Database cannot support this, then EF can't support as well.

There are two possible workarounds I can think of:

First:

public class Table2
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get; set;}

    public string RelatedTableName {get; set;}
    public int? Table1RowId {get; set;}
    public int? Table2RowId {get; set;}
    // ...
    public int? Table10RowId {get; set;}
}

Second

You can have subclasses for Table2, each having a foreign key for one of the tables. See here for how to implement inheritance in EF.

0
4/3/2020 7:05:13 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow