Polymorphic Relations in Entity Framework Core

c# entity-framework-core

Question

I have used Laravel in the past, and loved their polymorphic relations features.

Polymorphic relations allow a model to belong to more than one other model on a single association. For example, imagine users of your application can "comment" both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios.

Is there something similar in Entity Framework Core? I'm using their Code First Approach. Thanks

1
4
5/11/2017 9:08:29 AM

Accepted Answer

Maybe it is too late but could still be helpful for someone with the same question.

There sure is away of doing it and it is called TPH you can find more information on how to do it here https://docs.microsoft.com/en-us/ef/core/modeling/relational/inheritance.

However it has 1 major drawback if you want to use 1 table for 2 entities (2 parent tables) then you cannot have a ForeginKey Constraint on the Comments table.

The way you can do the setup is by having 2 columns on the Comments table 1 called EntityType and LinkId. The column EntityType would be the Discriminator column and it will tell you to which parent table this comment belongs either to a post or a video. and the LinkId will tell to which record in the Video table the Comment belongs to

Hope this answers it.

3
9/6/2018 4:13:55 PM

Popular Answer

I have the same problem, and I found 3 possible solutions:

  1. Implement some interfaces like IComentableObject.
  2. Model Comments table like this:

    Comments(CommentID, ..., PostID, VideoID)
    
  3. TPH pattern applies here?

Older question about this.



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