You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow more flexible conditional mapping for TPH and similar #10140
publicclassBaseType{publicstringCode{get;set;}publicstringType{get;set;}}publicclassChildType:BaseType{publicChildType()=>Type="ExplicitChild"
public string AdditionalData {get;set;}}
I am able to create a BaseType with a type value as "Implicit Child" and save it to the database, but when retrieving the information I can not get a reference to the "Implicit Child."
db.Set<BaseType>().ToList();
This is caused by the discriminator column being present in the where clause at all times.
Where [e].[Type] IN (N'ExplicitChild', N'BaseType')
I would expect one of the following
Prevent saving of arbitrary discriminator.
Don't check the discriminator column at all when using the base set without any constraints. <== preferred for my case
Further technical details
EF Core version: 2.0.0
Database Provider: SqlLite, MSSql
Operating system: Windows 10
IDE:Visual Studio 2017
Reacted by Jan Paolo Go, Pavel Stefanov, Yann Zahringer Ferrando, Theodore Zographos, Aay Jay Chan, Alfred Zaki, elmankross, Victor Lee, Yan , Luke Westfall and 25 more
@Tarig0 The normal pattern for TPH mapping in EF creates the discriminator property as a shadow property, and also marks it as read-only-after-save, both of which mean that to get to a place where the value can be modified arbitrarily requires some deviation from the norm. This is balanced with EF Core not blocking certain things that can be useful if you know what you are doing--for example, it's sometimes useful to be able to save a different discriminator value to cause a type change, but it's easy to shoot yourself in the foot if you're not careful.
To your first point, we could do some extra validation to prevent arbitrary values being saved, probably with some way to override this if needed, but at this point we don't think there is enough return on investment and it could also have perf implications for the update pipeline.
To your second point, we have talked a lot in the past about making the discriminator pattern just a specific case of more general conditional mapping, which would allow things like null/not null to be used. Since we don't seem to have an issue for this in the backlog I will re-purpose this issue for those cases.
Couple of questions for you:
Would an explicit list of discriminator values, instead of just one, work for you instead of the wildcard? In other words, you could say that values "A", "B", and "C" will all result in creation of the same type "X".
In such a case, when encountering type "X", which discriminator value would you expect EF to choose when none is set?
changed the title [-]TPH: Doesn't allow for wildcard discriminator on select[/-][+]Allow more flexible conditional mapping for TPH and similar[/+]on Oct 23, 2017
The case I was stretching for was to allow the end user to create new "types" at runtime which would act as the base type, until I could extend it later.
I would most likely end up using an enum, if I have to give a defined list at compile time, and have the base class be the default type. This would restrict me from doing things accidentally, and my previous case but I'm OK with adding a single line of code to a release/patch.
possible syntax for explicit list of discriminators.
typeEnumType{get;set}modelBuilder.Entity<BaseClass>().HasDiscriminator(e=>e.Type).HasValue<ExplicitChild>(typeEnum.ExplicitChild).HasValue<BaseClass>(new[]{typeEnum.Child1,typeEnum.Child2})// or params
Reacted by David Schruf, Theodore Zographos and Trey Briccetti
on your point on what would I expect when creating a base type, I would expect the discriminator to have to be explicitly defined, before attaching the entity.
Another option is to add a fluent function to the hasdiscriminator path, something like "HasDefaultDiscriminator" or have hasvalue have the overload that takes an ienumerable require a T param to be passed for the default
@alfred-zaki You could map only one class to the table that will contain all the corresponding properties. Alternatively you could use table sharing and map the extra columns to an owned type.
@AndriySvyrydAlternatively you could use table sharing and map the extra columns to an owned type. can you please guide me towards what that might be or look like.
I think the TPH Discriminator has some serious limitations / risks...
You can quietly "hide" data... which depending on your use case could be catastrophic - isComplete(false)
Or you can continually throw exceptions and require a code fix when new values are introduced to the discriminator field outside your control - isComplete(true)
We're Database First (many applications all interact with the same PGSQL database). We have TPH-like tables with optional embedded "linked" tables....
We Scaffold... and get a base_table, related_table_1, related_table_2 and related_table_3 entities.
Now, if we wanted to create a navigation property with strong typing and sql generation when querying, we tried something like this...
public partial class base_table_related_1 : base_table;
public partial class base_table_related_2 : base_table;
public partial class dbContext
{
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
modelBuilder.Entity<base_table>()
.HasDiscriminator(e => e.str_related_table)
.HasValue<base_table_related_1>(nameof(related_1_table))
.HasValue<base_table_related_2>(nameof(related_2_table))
// note related_table_3 is unmapped
.IsComplete(false);
}
}
I can then create navigation properties on either side and point the id_related_table at its counterpart primary key in the modelBuilder. It's Great!
Problem:
When executing the simple query below...
dbContext.base_table.ToList();
base_table records with str_related_table = related_table_3 are missing.
I would expect ALL records returned regardless of the discriminator. I'm not in control of the values that get put into base_table.str_related_table... new values can appear at anytime. I'm not expecting EF to marshal them into child types. But with IsComplete(false) setting, the Where statement is added to ensure only mapped discriminator values are returned.... so related_table_3 records are missing.
Ok... change that to .IsComplete(true) so the Where clause isn't added ..... now an exception is thrown.
Why is EF trying to marshal to child types? I asked for base_table.. and would expect base_table entities... of which all the derived types are.
If I did this...
dbContext.base_table_related_1.ToList();
I would expect base_table records that have the str_related_table = nameof(related_table_1) - (so yes.. a Where filter applied on a query to base_table). These should be of type base_table_related_1.
Similarly, when writing to the database.. I don't expect EF to do anything to mutations of base_table... and mutations of base_table_related_1 should have the discriminator str_related_table as a readonly property...
Again.. not expecting EF to validate the values we're trying to insert or read from base_table.str_related_table field... data integrity is the DB's responsibility... else I have to maintain that in too many places.
What would I like?
The TPH Discriminator pattern to help me construct stronger typed variants of base_table for use when I'd like to use them without me writing all the boiler plate
The discriminator implementation does not affect behavior of the base entity in the model... it adds new derived entities, with readonly discriminator property, to the model with minimal code
Therefore... unmapped discriminator values, including null, are moot - we just don't have the derived types for use in code...
This makes isComplete obsolete
We can actually solve this by implementing PGSQL table partitioning in the database (but you've hinted you will stop scaffolding child partitions - Recognize Partitions... - However... partitioning in the database is a heavy handed approach... I liked the light touch on the Model Builder.
To zero in on my bewilderment... from inheritance ...
When querying for derived entities, which use the TPH pattern, EF Core adds a predicate over discriminator column in the query. This filter makes sure that we don't get any additional rows for base types or sibling types not in the result. This filter predicate is skipped for the base entity type since querying for the base entity will get results for all the entities in the hierarchy. When materializing results from a query, if we come across a discriminator value, which isn't mapped to any entity type in the model, we throw an exception since we don't know how to materialize the results. This error only occurs if your database contains rows with discriminator values, which aren't mapped in the EF model. If you have such data, then you can mark the discriminator mapping in EF Core model as incomplete to indicate that we should always add filter predicate for querying any type in the hierarchy. IsComplete(false) call on the discriminator configuration marks the mapping to be incomplete.
A breakdown...
When querying for derived entities, which use the TPH pattern, EF Core adds a predicate over discriminator column in the query. This filter makes sure that we don't get any additional rows for base types or sibling types not in the result.
Great!
This filter predicate is skipped for the base entity type since querying for the base entity will get results for all the entities in the hierarchy
Awesome!
When materializing results from a query, if we come across a discriminator value, which isn't mapped to any entity type in the model, we throw an exception since we don't know how to materialize the results. This error only occurs if your database contains rows with discriminator values, which aren't mapped in the EF model.
umm.. why? Why are you materializing to derived types? Why not use the requested (base) entity type???
If you have such data, then you can mark the discriminator mapping in EF Core model as incomplete to indicate that we should always add filter predicate for querying any type in the hierarchy. IsComplete(false) call on the discriminator configuration marks the mapping to be incomplete.
So then I don't get all results.. just the mapped values / types...
Activity
ajcvickers commentedon Oct 23, 2017
@Tarig0 The normal pattern for TPH mapping in EF creates the discriminator property as a shadow property, and also marks it as read-only-after-save, both of which mean that to get to a place where the value can be modified arbitrarily requires some deviation from the norm. This is balanced with EF Core not blocking certain things that can be useful if you know what you are doing--for example, it's sometimes useful to be able to save a different discriminator value to cause a type change, but it's easy to shoot yourself in the foot if you're not careful.
To your first point, we could do some extra validation to prevent arbitrary values being saved, probably with some way to override this if needed, but at this point we don't think there is enough return on investment and it could also have perf implications for the update pipeline.
To your second point, we have talked a lot in the past about making the discriminator pattern just a specific case of more general conditional mapping, which would allow things like null/not null to be used. Since we don't seem to have an issue for this in the backlog I will re-purpose this issue for those cases.
Couple of questions for you:
[-]TPH: Doesn't allow for wildcard discriminator on select[/-][+]Allow more flexible conditional mapping for TPH and similar[/+]Tarig0 commentedon Oct 23, 2017
The case I was stretching for was to allow the end user to create new "types" at runtime which would act as the base type, until I could extend it later.
I would most likely end up using an enum, if I have to give a defined list at compile time, and have the base class be the default type. This would restrict me from doing things accidentally, and my previous case but I'm OK with adding a single line of code to a release/patch.
possible syntax for explicit list of discriminators.
Tarig0 commentedon Oct 23, 2017
on your point on what would I expect when creating a base type, I would expect the discriminator to have to be explicitly defined, before attaching the entity.
Another option is to add a fluent function to the hasdiscriminator path, something like "HasDefaultDiscriminator" or have hasvalue have the overload that takes an ienumerable require a T param to be passed for the default
Tarig0 commentedon Apr 9, 2018
I just realized there is nothing stopping me from generating the explicit list at dbcontext construct time, or at program start time.
I would have to gather the data either from configuration or manually query the database.
Either way it would allow me to do things with wild cards out side of EFcores engine.
Gazzo100uk commentedon Sep 23, 2018
Would this allow a discriminator to be configured across multiple columns, i.e. a composite discriminator?
Tarig0 commentedon Sep 24, 2018
Not with how it's been discussed, think that would be in an issue for type conversion.
ajcvickers commentedon Feb 4, 2019
Consider the case in #14601 when working on this.
ajcvickers commentedon Apr 15, 2019
See also multiple discriminator values in #15365
13 remaining items
AndriySvyryd commentedon Sep 3, 2020
@alfred-zaki If you are using TPH you need some discriminator
alfred-zaki commentedon Sep 3, 2020
@AndriySvyryd is there any workaround for my situation using 3.1.7? Seems like this feature not going to be worked on anytime soon if ever!
SuricateCan commentedon Sep 3, 2020
@alfred-zaki unfortunately no. You need to declare different classes for each discriminator.
The full feature is implemented in net 5.
AndriySvyryd commentedon Sep 4, 2020
@alfred-zaki You could map only one class to the table that will contain all the corresponding properties. Alternatively you could use table sharing and map the extra columns to an owned type.
alfred-zaki commentedon Sep 4, 2020
@AndriySvyryd
Alternatively you could use table sharing and map the extra columns to an owned type.can you please guide me towards what that might be or look like.akillablitz commentedon Mar 9, 2026
I've just stubbed my toe on this one.
I think the TPH Discriminator has some serious limitations / risks...
We're Database First (many applications all interact with the same PGSQL database). We have TPH-like tables with optional embedded "linked" tables....
We Scaffold... and get a base_table, related_table_1, related_table_2 and related_table_3 entities.
Now, if we wanted to create a navigation property with strong typing and sql generation when querying, we tried something like this...
I can then create navigation properties on either side and point the id_related_table at its counterpart primary key in the modelBuilder. It's Great!
Problem:
When executing the simple query below...
base_table records with str_related_table = related_table_3 are missing.
I would expect ALL records returned regardless of the discriminator. I'm not in control of the values that get put into
base_table.str_related_table... new values can appear at anytime. I'm not expecting EF to marshal them into child types. But withIsComplete(false)setting, the Where statement is added to ensure only mapped discriminator values are returned.... so related_table_3 records are missing.Ok... change that to
.IsComplete(true)so the Where clause isn't added ..... now an exception is thrown.Why is EF trying to marshal to child types? I asked for base_table.. and would expect base_table entities... of which all the derived types are.
If I did this...
I would expect base_table records that have the str_related_table = nameof(related_table_1) - (so yes.. a Where filter applied on a query to base_table). These should be of type
base_table_related_1.Similarly, when writing to the database.. I don't expect EF to do anything to mutations of base_table... and mutations of base_table_related_1 should have the discriminator str_related_table as a readonly property...
Again.. not expecting EF to validate the values we're trying to insert or read from base_table.str_related_table field... data integrity is the DB's responsibility... else I have to maintain that in too many places.
What would I like?
We can actually solve this by implementing PGSQL table partitioning in the database (but you've hinted you will stop scaffolding child partitions - Recognize Partitions... - However... partitioning in the database is a heavy handed approach... I liked the light touch on the Model Builder.
Thanks for reading!
akillablitz commentedon Mar 10, 2026
To zero in on my bewilderment... from inheritance ...
A breakdown...
Great!
Awesome!
umm.. why? Why are you materializing to derived types? Why not use the requested (base) entity type???
So then I don't get all results.. just the mapped values / types...