Skip to content

Relational: TPC inheritance mapping pattern #3170

Description

@rowanmiller

Consider configuring or issuing a warning to help with split identity seeding or shared sequence for the PK
FKs that point to a TPC entity type won't be enforced

  • Model support
  • Migrations support
  • Seed data support
  • SaveChanges support
  • Query support
  • End-to-end tests

Related: #17270 (comment)

Activity

  1. added this to the Backlog milestone on Sep 18, 2015
  2. wangkanai commented on Oct 21, 2015

    @wangkanai

    Can I make assumption that TPC is now going to be in RC? judged by the following work as expected

    public class Program
    {
        public void Main(string[] args)
        {
            var context = new InheritanceContext();
            var sarin = new Manager() {Name = "Sarin"};
            var siriphan = new Employee() {Name = "Siriphan", Manager = sarin};
            context.Managers.Add(sarin);
            context.Employees.Add(siriphan);
            context.SaveChanges();
        }
    }
    
    public class InheritanceContext : DbContext
    {
        public DbSet<Manager> Managers { get; set; }
        public DbSet<Employee> Employees { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=Ef7Inheritance;Trusted_Connection=True;");
        }
    }
    
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class Manager : Person
    {
        public Collection<Employee> Staffs { get; set; } 
    }
    
    public class Employee : Person
    {
        public Manager Manager { get; set; }
    }
    

    tpc
    This code is tested EntityFramework 7.0.0-beta8

  3. jimmymain commented on Oct 21, 2015

    @jimmymain

    awesome!

  4. rowanmiller commented on Oct 21, 2015

    @rowanmiller
    ContributorAuthor

    @wangkanai you are really just getting two separate entity types with an unmapped base type. They each have a separate key space and you won't be able to run a LINQ query on Person. So it's not really inheritance in EF, it's two separate entity types that happen to share a base type in the CLR for implementation.

  5. wangkanai commented on Oct 21, 2015

    @wangkanai

    If their are in same key space would that work well with sql server auto incremental primary key?

  6. rowanmiller commented on Oct 21, 2015

    @rowanmiller
    ContributorAuthor

    @wangkanai not with Identity (since that is per table) but you could use a sequence to generate values. What I really meant is that with true TPC you can't have Manager with Id = 1 and an Employee with Id = 1 since then you would have two instances of Person with Id = 1 (and EF would throw if you every tried to have this). In you setup this is possible since they aren't really in an inheritance hierarchy as far as EF is concerned.

  7. wangkanai commented on Oct 22, 2015

    @wangkanai

    @rowanmiller so if in theory we make a convention to use Id as identity key as Guid (in theory it unique), this should work right?

  8. weitzhandler commented on Oct 23, 2015

    @weitzhandler
    Contributor

    I'd wanna see TPT before TPC. As @rowanmiller said, @wangkanai example will be used in rare cases when you explicitly wanna keep the entities unmapped or whatever other reason I can't think of now.
    But TPT is even more important than TPH, because it can save a bunch of columns generated in each table completely DRYed and less-productive for some purposes.
    Lack of TPC made me start a new project in MVC5 and give up the new beta.
    Will this be implemented for the RC?

  9. rowanmiller commented on Oct 23, 2015

    @rowanmiller
    ContributorAuthor

    @wangkanai yep that would work. Just to be clear though... with the code you listed back at the start there is no need to ensure that the keys are unique between types since EF is treating them as completely separate types. But for true TPC, yes GUID keys is one option, or a sequence for numeric values, etc.

  10. jimmymain commented on Dec 4, 2015

    @jimmymain

    @weitzhandler I agree. Our database teams design with high normal forms in mind. TPT is what's required. I am of the opinion that TPC is a weak compromise compared to TPT. I often need to query base classes, and TPT makes this easy. A classic example of this is Martin Fowlers paper on Roles. Our clients will not be moving to EF until TPT is implemented.

  11. frogec commented on Jun 17, 2017

    @frogec

    What is the status on this feature? This turns out to be a really important feature in our case.

  12. AndriySvyryd commented on Sep 19, 2017

    @AndriySvyryd
    Member

    The implementation could be simplified if we used a database model #8258

  13. sthiakos commented on Nov 2, 2017

    @sthiakos

    +1 For Me - Note to all that you should "thumbs up" the initial post by @rowanmiller to vote up this issue. This and TPT is how DB's are/should be modeled.

  14. ite-jankl commented on Nov 2, 2017

    @ite-jankl

    The roadmap lists both TPC and TPT as high priority. Sad to not see either of these tickets in the 2.1 or 3.0 milestone.

  15. 92 remaining items

  16. marchy commented on Jun 16, 2022

    @marchy

    How are relationships from outside of an TPC hierarchy into any of its entities handled, given that no table is generated for the base/abstract entity?

    For example, are any of the following supported?
    (assuming the Animals entity hierarchy stated in the announcement post)

    // Example 1
    class SomeExternalEntity {
        // NOT SUPPORTED in TPC?
        public Animal Animal { get; private set; }
    }
    
    // Example 2
    class SomeOtherExternalEntity {
        // NOT SUPPORTED in TPC?
        public IList<Animal> Animals { get; private set; }
    }
    

    With both TPH and TPT, the following gets generated:

    // Example 1
    CREATE TABLE [dbo].[SomeExternalEntity](
        [AnimalID] [nvarchar](36) NOT NULL,
    ) ON [PRIMARY]
    ALTER TABLE [dbo].[SomeExternalEntity] ADD  CONSTRAINT [PK_dbo.SomeExternalEntity] PRIMARY KEY CLUSTERED 
    (
        [AnimalID] ASC
    )
    ALTER TABLE [dbo].[SomeExternalEntity]  WITH CHECK ADD  CONSTRAINT [FK_dbo.SomeExternalEntity_dbo.Animals_Id] FOREIGN KEY([Id])
    REFERENCES [dbo].[Animals] ([Id])
    
  17. ajcvickers commented on Jun 16, 2022

    @ajcvickers
    Contributor

    @marchy The relationship is handled normally, but no constraint is made in the database. We covered this in the community standup yesterday at around minute 58.

  18. eraffel-MDSol commented on Jun 17, 2022

    @eraffel-MDSol

    @ajcvickers With regard to the previous question, how will this work with deletes? Referencing the example given in the video, if I were to delete one of the animals, will the "Human" that references that animal as its favorite be deleted automatically, or would I have to manage preventing "orphan" records like that myself, since there's no FK constraint to enforce that.

  19. ajcvickers commented on Jun 17, 2022

    @ajcvickers
    Contributor

    @marchy The database won't perform automatic deletes, but EF will.

  20. bachratyg commented on Jun 17, 2022

    @bachratyg

    @ajcvickers does this mean that TPC uses Bulk (i.e. set-based) update/delete (without loading data into memory) #795 under the hood or that related entities need to be in the change tracker for cascade to work properly?

  21. ajcvickers commented on Jun 17, 2022

    @ajcvickers
    Contributor

    @bachratyg They need to be in the change tracker.

  22. bachratyg commented on Jun 17, 2022

    @bachratyg

    That means orphans have to be managed manually.

  23. ajcvickers commented on Jun 17, 2022

    @ajcvickers
    Contributor

    @bachratyg That depends on your definition of "manually". If data is appropriately loaded, then EF manages them. But if you are looking for a pattern that works well with database constructs like constraints and Identity keys, then TPC is not for you.

  24. bachratyg commented on Jun 17, 2022

    @bachratyg

    Data being appropriately loaded would mean a read lock on the principal row in all possible transactions modifying the relationship, some clever use of concurrency checks, or a business process that guarantees no concurrent phantom inserts. Either way serious steps should be taken to keep data consistent and that more or less covers my definition of "manually".

    Don't get me wrong, I don't feel either way about the implementation, I just want to be sure I fully understand the consequences.

  25. modified the milestones: , 7.0.0 on Nov 5, 2022
  26. removed their assignment
    on Mar 15, 2024
  27. added theissue type on Jun 15, 2025
  28. marked Income of inheritance TPC #22014 as a duplicate of this issue on Jun 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions