Skip to content

Allow more flexible conditional mapping for TPH and similar #10140

Description

@Tarig0

I have the following model

public class BaseType
    {
        public string Code {get;set;}
        public string Type {get;set;}
}
public class ChildType:BaseType
    {
        public ChildType()=> 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

Activity

  1. ajcvickers commented on Oct 23, 2017

    @ajcvickers
    Contributor

    @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?
  2. 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
  3. added this to the Backlog milestone on Oct 23, 2017
  4. Tarig0 commented on Oct 23, 2017

    @Tarig0
    Author

    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.

    typeEnum Type {get;set}
    
    modelBuilder.Entity<BaseClass>().HasDiscriminator(e=>e.Type)
       .HasValue<ExplicitChild>(typeEnum.ExplicitChild)
       .HasValue<BaseClass>(new [] {typeEnum.Child1,typeEnum.Child2}) // or params
  5. Tarig0 commented on Oct 23, 2017

    @Tarig0
    Author

    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

    typeEnum Type {get;set}
    
    modelBuilder.Entity<BaseClass>().HasDiscriminator(e=>e.Type)
       .HasValue<ExplicitChild>(typeEnum.ExplicitChild)
       .HasValue<BaseClass>(typeEnum.Child1,typeEnum.Child2)
       .HasDefaultDiscriminator<BaseClass>(typeEnum.Child1);
    
    modelBuilder.Entity<BaseClass>().HasDiscriminator(e=>e.Type)
       .HasValue<ExplicitChild>(typeEnum.ExplicitChild)
       .HasValue<BaseClass>(default:typeEnum.Child1, typeEnum.Child1,typeEnum.Child2)
  6. Tarig0 commented on Apr 9, 2018

    @Tarig0
    Author

    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.

  7. Gazzo100uk commented on Sep 23, 2018

    @Gazzo100uk

    Would this allow a discriminator to be configured across multiple columns, i.e. a composite discriminator?

  8. Tarig0 commented on Sep 24, 2018

    @Tarig0
    Author

    Not with how it's been discussed, think that would be in an issue for type conversion.

  9. ajcvickers commented on Feb 4, 2019

    @ajcvickers
    Contributor

    Consider the case in #14601 when working on this.

  10. ajcvickers commented on Apr 15, 2019

    @ajcvickers
    Contributor

    See also multiple discriminator values in #15365

  11. 13 remaining items

  12. AndriySvyryd commented on Sep 3, 2020

    @AndriySvyryd
    Member

    @alfred-zaki If you are using TPH you need some discriminator

  13. alfred-zaki commented on Sep 3, 2020

    @alfred-zaki

    @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!

  14. SuricateCan commented on Sep 3, 2020

    @SuricateCan

    @alfred-zaki unfortunately no. You need to declare different classes for each discriminator.
    The full feature is implemented in net 5.

  15. AndriySvyryd commented on Sep 4, 2020

    @AndriySvyryd
    Member

    @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.

  16. alfred-zaki commented on Sep 4, 2020

    @alfred-zaki

    @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.

  17. added theissue type on Jun 15, 2025
  18. akillablitz commented on Mar 9, 2026

    @akillablitz

    I've just stubbed my toe on this one.

    I think the TPH Discriminator has some serious limitations / risks...

    1. You can quietly "hide" data... which depending on your use case could be catastrophic - isComplete(false)
    2. 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....

    CREATE TABLE base_table ( 
    id_base_table BIGSERIAL,
    // fields
    id_related_table long,
    str_related_table text,
    CONSTRAINT pk_base_table PRIMARY KEY (id_base_table )
    );
    
    CREATE TABLE related_table_1 ( 
    id_related_table_1 BIGSERIAL,
    // fields
    CONSTRAINT pk_related_table_1 PRIMARY KEY (id_related_table_1)
    );
    
    CREATE TABLE related_table_2 ( 
    id_related_table_2 BIGSERIAL,
    // fields
    CONSTRAINT pk_related_table_2 PRIMARY KEY (id_related_table_2)
    );
    
    CREATE TABLE related_table_3 ( 
    id_related_table_3 BIGSERIAL,
    // fields
    CONSTRAINT pk_related_table_3 PRIMARY KEY (id_related_table_3)
    );
    

    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?

    1. 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
    2. 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
    3. Therefore... unmapped discriminator values, including null, are moot - we just don't have the derived types for use in code...
    4. 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.

    Thanks for reading!

  19. akillablitz commented on Mar 10, 2026

    @akillablitz

    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...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions