In my project I have a table Translation
that can have translations for any model. To achieve this, the table has two fields: Model
and ModelId
. The Model
property holds an integer indicating the type of the model and the ModelId
has the id of this model.
So, for example: the Product
table has modeltype id 1
. To get all translations for a product with id 317
, I search for translations with Model=1 AND ModelId=317
.
Now I would like to create this relation in Entity Framework Core. All my models inherit from the class BaseModel
that has a property ModelType
holding the id of the model type. This field is not mapped, so it is not available in the database.
I have tried to create the relation using fluent api, but it doesn't allow me to specify more columns to filter on.
modelBuilder.Entity<BaseModel>()
.HasMany<Translation>(bm => bm.Translations)
// Extra filters
Is there any way to create this relation without having to manually create a join for every query that requires translations?
Yes, there is. Use this:
Key1 and Key2 obviously need to be the keys to the relation and you may also need to define them as such (in the same order) for the Translation entity.
Since
modelBuilder.Entity<BaseModel>()
will useTPH
inheritance approach, I assume you are not using EF code first approach for database creation and you are using it to map your models to an existing database. Then you can try something like this:Models:
DbContext:
As you can see you can use
ModelTypeTranslations
to get Translations only for current model type.I should note this approach may have performance issues since it filters
Translations
byModelType
only in memory. Also I tried to avoid filtering in memory by usinglazy loading
but I got some exception even if I just installed that package without invokingoptionsBuilder.UseLazyLoadingProxies()
. I hope it will be fixed in the next releases.