Repository navigation
Entity Inheritance (TPH)
The entity-based bulk operations and the temp tables support entity inheritance with the mapping table-per-hierarchy (TPH). With TPH, the base type and all derived types of a hierarchy are stored in one table, and a discriminator column stores the type of each row. One call writes a collection that is typed as the base type and contains instances of the base type and of its derived types. The EF Core documentation describes how to configure TPH and the discriminator.
The following operations support TPH on SQL Server, PostgreSQL, MySQL and SQLite. Each linked section describes all rules of its operation. The operations need the bulk operation support (AddBulkOperationSupport(), see Bulk-Insert).
| Operation | Rules |
|---|---|
BulkInsertAsync with a collection of entities |
Bulk-Insert: Table-per-hierarchy (TPH) |
BulkUpdateAsync with a collection of entities |
Bulk-Update: Table-per-hierarchy (TPH) |
BulkInsertOrUpdateAsync with a collection of entities |
Bulk-Upsert: Table-per-hierarchy (TPH) |
BulkInsertIntoTempTableAsync and CreateTempTableAsync
|
Temp-Tables: Table-per-hierarchy (TPH) |
The examples on this page use the following hierarchy. Circle and Rectangle derive from Shape, and all three types are stored in the table Shapes. The discriminator is a shadow property of the type string. The properties Circle.Color and Rectangle.Color share one column.
public class Shape
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Circle : Shape
{
public int Radius { get; set; }
public string? Color { get; set; }
}
public class Rectangle : Shape
{
public int Width { get; set; }
public int Height { get; set; }
public string? Color { get; set; }
}
public class DemoDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Shape>(builder =>
{
builder.ToTable("Shapes");
builder.HasDiscriminator<string>("Discriminator")
.HasValue<Shape>("Shape")
.HasValue<Circle>("Circle")
.HasValue<Rectangle>("Rectangle");
});
// both properties use the column "Color"
modelBuilder.Entity<Circle>().Property(c => c.Color).HasColumnName("Color");
modelBuilder.Entity<Rectangle>().Property(r => r.Color).HasColumnName("Color");
}
}-
One call for the whole hierarchy: Pass a collection that is typed as the base type, for example
List<Shape>. The collection can contain instances of all types of the hierarchy. The entities do not need to be attached to theDbContext. -
Columns: The default columns are the columns of the type of the collection, of its base types and of its derived types. A column that the type of a row does not have gets
NULL. -
Type of a row: The type of every entity is resolved by the rule of
SaveChanges. It is the entity type of the CLR type, or of the nearest CLR base class that is mapped. Therefore an instance of an unmapped subclass or of a proxy type is written as its nearest mapped type. - Discriminator: Bulk insert, the insert part of the upsert and the temp tables always write the discriminator. Its value is the value that the model configures for the type of the row. The library never reads the value of a CLR discriminator property. Bulk update and the update part of the upsert never change the discriminator, because EF Core treats it as read-only after the row was saved.
-
Shared columns: Two sibling types can map a property to the same column, for example
Circle.ColorandRectangle.Color. Such a column appears once in every statement, and every row writes the property of its own type. -
Members of derived types:
PropertiesToInsert,PropertiesToUpdate,IEntityPropertiesProvider.IncludeandIEntityPropertiesProvider.Excludeaccept a member of a derived type through a cast, for examples => ((Circle)s).Radius. Theasoperator works as well, and the cast can be used inside an anonymous object. A member of one sibling type selects the shared column for all rows. -
Key members: A member of a key list (
KeyProperties,propertiesToMatchOnand the primary key of a temp table withIPrimaryKeyPropertiesProvider) must be declared on the type of the collection or on one of its base types. Such a member also works through a cast to a derived type, for examples => ((Circle)s).Id. It also works as aMemberInfothat is passed toIEntityPropertiesProvider.Include(IReadOnlyList<MemberInfo>)and that is reflected through a derived type, an unmapped subclass or a proxy type. A key member that is declared on a derived type throws aNotSupportedException("... cannot be used as a key property ...").
The examples use the extension methods of DbContext, which work with every provider.
List<Shape> shapes =
[
new Circle { Id = Guid.NewGuid(), Name = "c1", Radius = 3, Color = "red" },
new Rectangle { Id = Guid.NewGuid(), Name = "r1", Width = 4, Height = 5, Color = "blue" }
];
// writes the columns of all types of the hierarchy and the discriminator
await ctx.BulkInsertAsync(shapes);
// writes the selected columns and the discriminator
await ctx.BulkInsertAsync(shapes, s => new { s.Id, s.Name, ((Circle)s).Radius });List<Shape> shapes =
[
new Circle { Id = circleId, Name = "c1", Radius = 5, Color = "green" },
new Rectangle { Id = rectangleId, Name = "r1", Width = 6, Height = 7 }
];
// updates all columns except the key and the discriminator
await ctx.BulkUpdateAsync(shapes);
// updates the selected columns; the column "Radius" of the rectangle row is set to NULL
await ctx.BulkUpdateAsync(shapes, propertiesToUpdate: s => new { s.Name, ((Circle)s).Radius });List<Shape> shapes =
[
new Circle { Id = existingCircleId, Name = "c1", Radius = 5 },
new Rectangle { Id = Guid.NewGuid(), Name = "r1", Width = 6, Height = 7 }
];
// inserts the new rows with the discriminator and updates the existing rows without it
await ctx.BulkInsertOrUpdateAsync(shapes);
// updates the selected columns of the existing rows and matches the rows by "Id"
await ctx.BulkInsertOrUpdateAsync(shapes,
propertiesToUpdate: s => new { s.Name, ((Circle)s).Radius },
propertiesToMatchOn: s => s.Id);List<Shape> shapes =
[
new Circle { Id = Guid.NewGuid(), Name = "c1", Radius = 3 },
new Rectangle { Id = Guid.NewGuid(), Name = "r1", Width = 4, Height = 5 }
];
// all-in-one: creates the temp table with the columns of the hierarchy and the discriminator
await using var tempTable = await ctx.BulkInsertIntoTempTableAsync(shapes);
// returns a "Circle" and a "Rectangle"
List<Shape> loaded = await tempTable.Query.ToListAsync();
// two-step: creates an empty temp table first and inserts the rows later
await using var emptyTempTable = await ctx.CreateTempTableAsync<Shape>(new TempTableCreationOptions());
await ctx.BulkInsertIntoTempTableAsync(shapes, emptyTempTable);- Type of an existing row: The library does not check the type of an existing row. When an entity has another type than the existing row with the same key, the discriminator keeps the old type, and the columns are written as described above. The caller is responsible for passing entities of the type of the existing rows.
-
Invalid rows: An entity whose type is not a concrete type of the collection type throws an
InvalidOperationException. Examples are an instance whose nearest mapped type is abstract, and an instance of a sibling type when the collection is typed as a type in the middle of the hierarchy. The type is checked while the rows are sent. - Atomicity: Bulk insert and temp tables stop at an invalid row after the earlier rows were sent. The atomicity is the same as for every other exception of the source, for example a property getter that throws. Bulk update and upsert on SQL Server, PostgreSQL and MySQL send all rows into a temp table first, so the target table is unchanged when a row is invalid. SQLite writes the target rows one after another. When the operation runs in its own transaction, SQLite rolls them back. A transaction of the caller keeps the rows that were written until the caller rolls it back.
-
Owned types: Owned types that are declared on the type of the collection or on one of its base types follow the rules for owned types without inheritance. Bulk insert writes them on all providers. Bulk update and upsert throw a
NotSupportedExceptionon SQL Server, PostgreSQL and MySQL. SQL Server and PostgreSQL throw "Temp tables don't support owned entities." MySQL throws "MySQL bulk update and upsert do not support owned entities mapped to separate tables." for an owned type in a separate table and "Temp tables don't support owned entities." for an inlined owned type. SQLite bulk update and upsert write the inlined owned types. Temp tables do not support owned types. An owned type that is declared on a derived type throws aNotSupportedExceptionbefore the first statement on all providers. - Shadow properties: A shadow property other than the discriminator needs an attached entity, as for an entity type without inheritance (see Bulk-Insert: Shadow Properties).
-
Root type without a table: The root type of the hierarchy must be mapped to a table. Otherwise the operation throws an
InvalidOperationException("The entity type '...' is not mapped to a table."). -
Custom data reader factory: A replaced
IEntityDataReaderFactorymust implement the overload with the parameterIEntityType. Otherwise a TPH entity type throws aNotSupportedException(see Bulk-Insert: Table-per-hierarchy (TPH)). - Other inheritance mappings: Only TPH is supported. The bulk operations and the temp tables have no special handling and no check for table-per-type (TPT) and table-per-concrete-type (TPC) mappings. They handle such an entity type like an entity type without inheritance.
- Query-based operations: Bulk update from a query and bulk insert from a query have no special handling for TPH. The rules on this page apply to the operations with a collection of entities only.
- Temp-Tables
- Bulk-Insert
- Bulk-Update
- Bulk-Upsert (Insert-or-Update)
- Entity Inheritance (TPH) (SQL Server, PostgreSQL, MySQL, SQLite)
- Truncate Tables