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
By default, EF maps the inheritance using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents.
The Entity Framework Core Fluent API HasDiscriminator method is used to configure aspects of the discriminator column in a table that represents an inheritance hierarchy. By convention, a discriminator column will be configured to use a string data type will be named "Discriminator".
So what is a polymorphic relationship? A polymorphic relationship is where a model can belong to more than one other model on a single association. To clarify this, let's create an imaginary situation where we have a Topic and a Post model. Users can leave comments on both topics and posts.
This tutorial demonstrates how to implement TPH inheritance. TPH is the only inheritance pattern that the Entity Framework Core supports.
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.
I have the same problem, and I found 3 possible solutions:
IComentableObject
.Model Comments table like this:
Comments(CommentID, ..., PostID, VideoID)
TPH pattern applies here?
Older question about this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With