1

I apologize if the title does not make sense. I will try my best to explain what I am trying to achieve.

I have these two entities that both have a collection of the same entity type. enter image description here

I hoping to see if there is a way in the override of OnModelCreating to tell EFCore that Entity1 and Entity2 both use the Entity3 DB table to populate its collection.

When querying to populate Entity1's SubEntites collections it should do something like the following. The type column will be mapped to an enum.

// When populating Entity1
SELECT * FROM Entity3 WHERE ForeignID = [Entity1.ID] AND Type  = 1;

// When populating Entity2
SELECT * FROM Entity3 WHERE ForeignID = [Entity1.ID] AND Type  = 2;
  • You say that `Entity3` has a `ForeignId` column with a foreign key. To which table does this foreign key points to? Does your `Entity1` and `Entity2` entity/table share a common base table/entity? Is it an option to use multiple nullable foreign keys in the `Entity3` column? – Progman Feb 08 '22 at 20:30
  • Entity3's Foreign Key points to both Entity1 and Entity2. Other than sharing the same collection type Entity1 and Entity2 are different. – Richard Eagle Feb 08 '22 at 20:33
  • How have you created the foreign key in `Entity3` that it reference both PKs from `Entity1` and `Entity2`? – Progman Feb 08 '22 at 20:36
  • No, I have not tried any of this is code yet because I figured EFCore would yell at me for having the same column act as a FK to two different tables. – Richard Eagle Feb 08 '22 at 20:38
  • Please see: [Why is “Is it possible to…” a poorly worded question?](https://softwareengineering.meta.stackexchange.com/q/7273). – Progman Feb 08 '22 at 20:47
  • The real question is can you create such FK in relational database. The answer is no, hence the same is with EF Core - currently it does not support relationship which cannot be enforced with physical FK relationship in database. What you are asking for is called "polymorphic association", you can find many posts pointing out it is not supported by *any* EF ("classic" or Core) version. – Ivan Stoev Feb 09 '22 at 06:52

0 Answers0