Entity Framework Core – Inheritance – Table-Per-Type (TPT) Is Not Supported, Is It? (Part 2 – Database First)

In the previous post we have created 2 Entity Framework Core (EF Core) models with a code first approach. One model was using the Table-per-Hierarchy (TPH) pattern and the other one Table-per-Type (TPT). In this post we want to approach a more common scenario we see in customer projects: we are using the database first approach now. All demos are on Github.

In diesem Artikel:

pg
Pawel Gerr ist Architekt und Consultant bei Thinktecture. Er hat sich auf .NET Core Backends spezialisiert und kennt Entity Framework von vorne bis hinten.

Business data model

The business data model is the same as in the previous post. We have 3 DTOs: Person, Customer and Employee.

				
					public class PersonDto
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class CustomerDto : PersonDto
{
    public DateTime DateOfBirth { get; set; }
}

public class EmployeeDto : PersonDto
{
    public decimal Turnover { get; set; }
}
				
			

Table-per-Hierarchy (TPH)

We start with the Table-per-Hierarchy pattern. Given is a table People containing all columns from all DTOs incl. 1 column Discriminator to be able to distinguish the customers from employees.

Remark: we are using nvarchar(max) for the sake of simplicity.

				
					TABLE People
(
    Id uniqueidentifier NOT NULL PRIMARY KEY,
    FirstName nvarchar(max) NULL,
    LastName nvarchar(max) NULL,
    DateOfBirth datetime2(7) NULL,
    Turnover decimal(18, 2) NULL,
    Discriminator nvarchar(max) NOT NULL
)
				
			

With the following command we let EF Core scaffold the entities (or rather the entity) and the database context:

				
					dotnet ef dbcontext scaffold "Server=(local);Database=TphDemo;Trusted_Connection=True" Microsoft.EntityFrameworkCore.SqlServer -f -c ScaffoldedTphDbContext --context-dir ./TphModel/DatabaseFirst -o ./TphModel/DatabaseFirst -p ./../../EntityFramework.Demo.csproj -s ./../../EntityFramework.Demo.csproj
				
			

The result is not the one we might have expected but is pretty reasonable. The scaffolding creates just 1 entity People with all fields in it because there is no way for EF Core to guess that the table contains 3 entities and not just 1.

				
					public class People
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public decimal? Turnover { get; set; }
    public string Discriminator { get; set; }
}

				
			

First, let’s fix the name of the entity because the name should be Person not People.

For that we create a class that does the pluralization/singularization and register it with the so-called IDesignTimeServices. The implementation of IDesignTimeServices doesn’t need any kind of registration, EF Core will find it automatically. The actual pluralization/singularization will be done by the 3rd party-library Inflector.

				
					public class Pluralizer : IPluralizer
{
    public string Pluralize(string identifier)
    {
        // Inflector needs some help with "People" otherwise we get "Peoples"
        if (identifier == "People")
            return identifier;

        return Inflector.Inflector.Pluralize(identifier);
  }

    public string Singularize(string identifier)
    {
        return Inflector.Inflector.Singularize(identifier);
    }
}

public class DesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection services)
    {
        services.AddSingleton<IPluralizer, Pluralizer>();
    }
}
				
			

Now, the generated entity gets the name Person – but to make the model right we have to split the class in 3, manually. After manual adjustments we have 2 options: switch to code first approach or adjust the classes manually after every scaffolding to apply the changes from database. The adjusted code is virtually identical to the one of code first approach but this time the Descriminator is defined explicitly.

Remark: I’ve renamed Person to PersonTph so the names are the same as in the previous blog post.

				
					public class PersonTph
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Discriminator { get; set; }
}

public class CustomerTph : PersonTph
{
  public DateTime DateOfBirth { get; set; }
}

public class EmployeeTph : PersonTph
{
  public decimal Turnover { get; set; }
}
				
			

The generated database context needs some adjustments as well because DbSets for customers and employees are missing and the field Discriminator has to be defined as one.

				
					public partial class ScaffoldedTphDbContext : DbContext
{
    public virtual DbSet<Person> People { get; set; }

    public ScaffoldedTphDbContext(DbContextOptions<ScaffoldedTphDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>(entity =>
                      {
                        entity.Property(e => e.Id).ValueGeneratedNever();
                        entity.Property(e => e.Discriminator).IsRequired();
                      });
    }
}
				
			

As with the entities, the only change – compared to code first approach – is the explicit definition of the Discriminator.

				
					public class ScaffoldedTphDbContext : DbContext
{
  public virtual DbSet<PersonTph> People { get; set; }
  public virtual DbSet<CustomerTph> Customers { get; set; }
  public virtual DbSet<EmployeeTph> Employees { get; set; }

  public ScaffoldedTphDbContext(DbContextOptions<ScaffoldedTphDbContext> options)
    : base(options)
  {
  }

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<PersonTph>(entity => entity.Property(e => e.Id).ValueGeneratedNever());
    modelBuilder.Entity<PersonTph>()
            .HasDiscriminator(person => person.Discriminator)
            .HasValue<PersonTph>(nameof(PersonTph))
            .HasValue<CustomerTph>(nameof(CustomerTph))
            .HasValue<EmployeeTph>(nameof(EmployeeTph));
  }
}
				
			

Table-per-Type (TPT)

Having a database using the TPT pattern we start off 3 with tables:

				
					TABLE People
(
    Id uniqueidentifier NOT NULL PRIMARY KEY,
    FirstName nvarchar(max) NULL,
    LastName nvarchar(max) NULL
)

TABLE Customers
(
    Id uniqueidentifier NOT NULL
        PRIMARY KEY
        FOREIGN KEY REFERENCES People (Id),
    DateOfBirth datetime2(7) NOT NULL
)

TABLE Employees
(
    Id uniqueidentifier NOT NULL
        PRIMARY KEY
        FOREIGN KEY REFERENCES People (Id),
    Turnover [decimal](18, 2) NOT NULL
)
				
			

With the following command we create the entities and the database context:

				
					dotnet ef dbcontext scaffold "Server=(local);Database=TptDemo;Trusted_Connection=True" Microsoft.EntityFrameworkCore.SqlServer -f -c ScaffoldedTptDbContext --context-dir ./TptModel/DatabaseFirst -o ./TptModel/DatabaseFirst -p ./../../EntityFramework.Demo.csproj -s ./../../EntityFramework.Demo.csproj
				
			

The scaffolder generates 3 entities that are almost correct. The only flaw is the name of the navigational property IdNavigation pointing to the base class Person.

				
					public partial class Person
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Customer Customer { get; set; }
    public Employee Employee { get; set; }
}

public partial class Employee
{
    public Guid Id { get; set; }
    public decimal Turnover { get; set; }

    public Person IdNavigation { get; set; }
}

public partial class Customer
{
    public Guid Id { get; set; }
    public DateTime DateOfBirth { get; set; }

    public Person IdNavigation { get; set; }
}
				
			

Luckily, this issue is very easy to fix by implementing ICandidateNamingService and registering it with IDesignTimeServices.

				
					public class CustomCandidateNamingService : CandidateNamingService
{
    public override string GetDependentEndCandidateNavigationPropertyName(IForeignKey foreignKey)
    {
        if(foreignKey.PrincipalKey.IsPrimaryKey())
            return foreignKey.PrincipalEntityType.ShortName();

        return base.GetDependentEndCandidateNavigationPropertyName(foreignKey);
  }
}

public class DesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection services)
    {
        services.AddSingleton<IPluralizer, Pluralizer>()
            .AddSingleton<ICandidateNamingService, CustomCandidateNamingService>();
    }
}

				
			

After re-running the scaffolder, we get the expected results:

				
					public class Customer
{
    public Guid Id { get; set; }
    public DateTime DateOfBirth { get; set; }

    public Person Person { get; set; }
}
				
			
				
					public partial class Employee
{
    public Guid Id { get; set; }
    public decimal Turnover { get; set; }

    public Person Person { get; set; }
}
				
			

The last part is the database context. Fortunately, we don’t have to change anything.

				
					public partial class ScaffoldedTptDbContext : DbContext
{
  public virtual DbSet<Customer> Customers { get; set; }
  public virtual DbSet<Employee> Employees { get; set; }
  public virtual DbSet<Person> People { get; set; }

  public ScaffoldedTptDbContext(DbContextOptions<ScaffoldedTptDbContext> options)
    : base(options)
  {
  }

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Customer>(entity =>
                        {
                          entity.Property(e => e.Id).ValueGeneratedNever();

                          entity.HasOne(d => d.Person)
                              .WithOne(p => p.Customer)
                              .HasForeignKey<Customer>(d => d.Id);
                        });

    modelBuilder.Entity<Employee>(entity =>
                        {
                          entity.Property(e => e.Id).ValueGeneratedNever();

                          entity.HasOne(d => d.Person)
                              .WithOne(p => p.Employee)
                              .HasForeignKey<Employee>(d => d.Id);
                        });

    modelBuilder.Entity<Person>(entity => 
                        {
                          entity.Property(e => e.Id).ValueGeneratedNever());
                        });
  }
}
				
			

With TPT we can but don’t have to switch to code first approach because we can regenerate the entities and the database context at any time.

Conclusion

Database first approach works best with TPT, with TPH not so much because a relational database knows nothing about any inheritance. With TPT there is just one minor issue but thanks to the great job of the Entity Framework team we can adjust the code generation as we want without the need to copy all the code of Entity Framework Core.

Kostenloser
Newsletter

Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Newsletter Anmeldung
Diese Artikel könnten Sie interessieren
Database Access with Sessions
.NET
KP-round

Data Access in .NET Native AOT with Sessions

.NET 8 brings Native AOT to ASP.NET Core, but many frameworks and libraries rely on unbound reflection internally and thus cannot support this scenario yet. This is true for ORMs, too: EF Core and Dapper will only bring full support for Native AOT in later releases. In this post, we will implement a database access layer with Sessions using the Humble Object pattern to get a similar developer experience. We will use Npgsql as a plain ADO.NET provider targeting PostgreSQL.
15.11.2023
Old computer with native code
.NET
KP-round

Native AOT with ASP.NET Core – Overview

Originally introduced in .NET 7, Native AOT can be used with ASP.NET Core in the upcoming .NET 8 release. In this post, we look at the benefits and drawbacks from a general perspective and perform measurements to quantify the improvements on different platforms.
02.11.2023
.NET
KP-round

Optimize ASP.NET Core memory with DATAS

.NET 8 introduces a new Garbage Collector feature called DATAS for Server GC mode - let's make some benchmarks and check how it fits into the big picture.
09.10.2023
.NET CORE
pg

Incremental Roslyn Source Generators: High-Level API – ForAttributeWithMetadataName – Part 8

With the version 4.3.1 of Microsoft.CodeAnalysis.* Roslyn provides a new high-level API - the method "ForAttributeWithMetadataName". Although it is just 1 method, still, it addresses one of the biggest performance issue with Source Generators.
16.05.2023
AI
favicon

Integrating AI Power into Your .NET Applications with the Semantic Kernel Toolkit – an Early View

With the rise of powerful AI models and services, questions come up on how to integrate those into our applications and make reasonable use of them. While other languages like Python already have popular and feature-rich libraries like LangChain, we are missing these in .NET and C#. But there is a new kid on the block that might change this situation. Welcome Semantic Kernel by Microsoft!
03.05.2023
.NET
sg

.NET 7 Performance: Regular Expressions – Part 2

There is this popular quote by Jamie Zawinski: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems."

In this second article of our short performance series, we want to look at the latter one of those problems.
25.04.2023