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
Copy file name to clipboardexpand all lines: entity-framework/core/modeling/generated-properties.md
+1-1
Original file line number
Diff line number
Diff line change
@@ -39,7 +39,7 @@ The above creates a *virtual* computed column, whose value is computed every tim
39
39
40
40
By convention, non-composite primary keys of type short, int, long, or Guid are set up to have values generated for inserted entities if a value isn't provided by the application. Your database provider typically takes care of the necessary configuration; for example, a numeric primary key in SQL Server is automatically set up to be an IDENTITY column.
41
41
42
-
For more information, [see the documentation about keys](xref:core/modeling/keys).
42
+
For more information, [see the documentation about keys](xref:core/modeling/keys) and [guidance for specific inheritance mapping strategies](xref:core/modeling/inheritance#key-generation).
Copy file name to clipboardexpand all lines: entity-framework/core/modeling/inheritance.md
+262-2
Original file line number
Diff line number
Diff line change
@@ -2,7 +2,7 @@
2
2
title: Inheritance - EF Core
3
3
description: How to configure entity type inheritance using Entity Framework Core
4
4
author: AndriySvyryd
5
-
ms.date: 10/01/2020
5
+
ms.date: 10/10/2022
6
6
uid: core/modeling/inheritance
7
7
---
8
8
# Inheritance
@@ -61,12 +61,15 @@ By default, when two sibling entity types in the hierarchy have a property with
61
61
## Table-per-type configuration
62
62
63
63
> [!NOTE]
64
-
> The table-per-type (TPT) feature was introduced in EF Core 5.0. Table-per-concrete-type (TPC) is supported by EF6, but is not yet supported by EF Core.
64
+
> The table-per-type (TPT) feature was introduced in EF Core 5.0.
65
65
66
66
In the TPT mapping pattern, all the types are mapped to individual tables. Properties that belong solely to a base type or derived type are stored in a table that maps to that type. Tables that map to derived types also store a foreign key that joins the derived table with the base table.
> Instead of calling `ToTable` on each entity type you can call `modelBuilder.Entity<Blog>().UseTptMappingStrategy()` on each root entity type and the table names will be generated by EF.
72
+
70
73
EF will create the following database schema for the model above.
71
74
72
75
```sql
@@ -93,3 +96,260 @@ If you are employing bulk configuration you can retrieve the column name for a s
93
96
94
97
> [!WARNING]
95
98
> In many cases, TPT shows inferior performance when compared to TPH. [See the performance docs for more information](xref:core/performance/modeling-for-performance#inheritance-mapping).
99
+
100
+
> [!CAUTION]
101
+
> Columns for a derived type are mapped to different tables, therefore composite FK constraints and indexes that use both the inherited and declared properties cannot be created in the database.
102
+
103
+
## Table-per-concrete-type configuration
104
+
105
+
> [!NOTE]
106
+
> The table-per-concrete-type (TPC) feature was introduced in EF Core 7.0.
107
+
108
+
In the TPC mapping pattern, all the types are mapped to individual tables. Each table contains columns for all properties on the corresponding entity type. This addresses some common performance issues with the TPT strategy.
109
+
110
+
> [!TIP]
111
+
> The EF Team demonstrated and talked in depth about TPC mapping in an episode of the [.NET Data Community Standup](https://aka.ms/efstandups). As with all Community Standup episodes, you can [watch the TPC episode now on YouTube](https://youtu.be/HaL6DKW1mrg).
> Instead of calling `ToTable` on each entity type just calling `modelBuilder.Entity<Blog>().UseTpcMappingStrategy()` on each root entity type will generate the table names by convention.
117
+
118
+
EF will create the following database schema for the model above.
119
+
120
+
```sql
121
+
CREATE TABLE [Blogs] (
122
+
[BlogId] intNOT NULL DEFAULT (NEXT VALUE FOR [BlogSequence]),
123
+
[Url] nvarchar(max) NULL,
124
+
CONSTRAINT [PK_Blogs] PRIMARY KEY ([BlogId])
125
+
);
126
+
127
+
CREATE TABLE [RssBlogs] (
128
+
[BlogId] intNOT NULL DEFAULT (NEXT VALUE FOR [BlogSequence]),
129
+
[Url] nvarchar(max) NULL,
130
+
[RssUrl] nvarchar(max) NULL,
131
+
CONSTRAINT [PK_RssBlogs] PRIMARY KEY ([BlogId])
132
+
);
133
+
```
134
+
135
+
### TPC database schema
136
+
137
+
The TPC strategy is similar to the TPT strategy except that a different table is created for every *concrete* type in the hierarchy, but tables are **not** created for *abstract* types - hence the name “table-per-concrete-type”. As with TPT, the table itself indicates the type of the object saved. However, unlike TPT mapping, each table contains columns for every property in the concrete type and its base types. TPC database schemas are denormalized.
138
+
139
+
For example, consider mapping this hierarchy:
140
+
141
+
<!--
142
+
public abstract class Animal
143
+
{
144
+
protected Animal(string name)
145
+
{
146
+
Name = name;
147
+
}
148
+
149
+
public int Id { get; set; }
150
+
public string Name { get; set; }
151
+
public abstract string Species { get; }
152
+
153
+
public Food? Food { get; set; }
154
+
}
155
+
156
+
public abstract class Pet : Animal
157
+
{
158
+
protected Pet(string name)
159
+
: base(name)
160
+
{
161
+
}
162
+
163
+
public string? Vet { get; set; }
164
+
165
+
public ICollection<Human> Humans { get; } = new List<Human>();
When using SQL Server, the tables created for this hierarchy are:
235
+
236
+
```sql
237
+
CREATE TABLE [Cats] (
238
+
[Id] intNOT NULL DEFAULT (NEXT VALUE FOR [AnimalSequence]),
239
+
[Name] nvarchar(max) NOT NULL,
240
+
[FoodId] uniqueidentifier NULL,
241
+
[Vet] nvarchar(max) NULL,
242
+
[EducationLevel] nvarchar(max) NOT NULL,
243
+
CONSTRAINT [PK_Cats] PRIMARY KEY ([Id]));
244
+
245
+
CREATE TABLE [Dogs] (
246
+
[Id] intNOT NULL DEFAULT (NEXT VALUE FOR [AnimalSequence]),
247
+
[Name] nvarchar(max) NOT NULL,
248
+
[FoodId] uniqueidentifier NULL,
249
+
[Vet] nvarchar(max) NULL,
250
+
[FavoriteToy] nvarchar(max) NOT NULL,
251
+
CONSTRAINT [PK_Dogs] PRIMARY KEY ([Id]));
252
+
253
+
CREATE TABLE [FarmAnimals] (
254
+
[Id] intNOT NULL DEFAULT (NEXT VALUE FOR [AnimalSequence]),
255
+
[Name] nvarchar(max) NOT NULL,
256
+
[FoodId] uniqueidentifier NULL,
257
+
[Value] decimal(18,2) NOT NULL,
258
+
[Species] nvarchar(max) NOT NULL,
259
+
CONSTRAINT [PK_FarmAnimals] PRIMARY KEY ([Id]));
260
+
261
+
CREATE TABLE [Humans] (
262
+
[Id] intNOT NULL DEFAULT (NEXT VALUE FOR [AnimalSequence]),
263
+
[Name] nvarchar(max) NOT NULL,
264
+
[FoodId] uniqueidentifier NULL,
265
+
[FavoriteAnimalId] intNULL,
266
+
CONSTRAINT [PK_Humans] PRIMARY KEY ([Id]));
267
+
```
268
+
269
+
Notice that:
270
+
271
+
- There are no tables for the `Animal` or `Pet` types, since these are `abstract` in the object model. Remember that C# does not allow instances of abstract types, and there is therefore no situation where an abstract type instance will be saved to the database.
272
+
- The mapping of properties in base types is repeated for each concrete type. For example, every table has a `Name` column, and both Cats and Dogs have a `Vet` column.
273
+
274
+
- Saving some data into this database results in the following:
| 6 | Arthur | 59b495d4-0414-46bf-d4ad-08da7aca624f | 1 |
302
+
| 9 | Katie | null | 8 |
303
+
304
+
Notice that unlike with TPT mapping, all the information for a single object is contained in a single table. And, unlike with TPH mapping, there is no combination of column and row in any table where that is never used by the model. We'll see below how these characteristics can be important for queries and storage.
305
+
306
+
### Key generation
307
+
308
+
The inheritance mapping strategy chosen has consequences for how primary key values are generated and managed. Keys in TPH are easy, since each entity instance is represented by a single row in a single table. Any kind of key value generation can be used, and no additional constraints are needed.
309
+
310
+
For the TPT strategy, there is always a row in the table mapped to the base type of the hierarchy. Any kind of key generation can be used on this row, and the keys for other tables are linked to this table using foreign key constraints.
311
+
312
+
Things get a bit more complicated for TPC. First, it’s important to understand that EF Core requires that all entities in a hierarchy have a unique key value, even if the entities have different types. For example, using our example model, a Dog cannot have the same Id key value as a Cat. Second, unlike TPT, there is no common table that can act as the single place where key values live and can be generated. This means a simple `Identity` column cannot be used.
313
+
314
+
For databases that support sequences, key values can be generated by using a single sequence referenced in the default constraint for each table. This is the strategy used in the TPC tables shown above, where each table has the following:
315
+
316
+
```sql
317
+
[Id] intNOT NULL DEFAULT (NEXT VALUE FOR [AnimalSequence])
318
+
```
319
+
320
+
`AnimalSequence` is a database sequence created by EF Core. This strategy is used by default for TPC hierarchies when using the EF Core database provider for SQL Server. Database providers for other databases that support sequences should have a similar default. Other key generation strategies that use sequences, such as Hi-Lo patterns, may also be used with TPC.
321
+
322
+
While standard Identity columns don't work with TPC, it is possible to use Identity columns if each table is configured with an appropriate seed and increment such that the values generated for each table will never conflict. For example:
> Using this strategy makes it harder to add derived types later as it requires the total number of types in the hierarchy to be known beforehand.
334
+
335
+
SQLite does not support sequences or Identity seed/increment, and hence integer key value generation is not supported when using SQLite with the TPC strategy. However, client-side generation or globally unique keys - such as GUIDs - are supported on any database, including SQLite.
336
+
337
+
### Foreign key constraints
338
+
339
+
The TPC mapping strategy creates a denormalized SQL schema - this is one reason why some database purists are against it. For example, consider the foreign key column `FavoriteAnimalId`. The value in this column must match the primary key value of some animal. This can be enforced in the database with a simple FK constraint when using TPH or TPT. For example:
But when using TPC, the primary key for any given animal is stored in the table corresponding to the concrete type of that animal. For example, a cat's primary key is stored in the `Cats.Id` column, while a dog's primary key is stored in the `Dogs.Id` column, and so on. This means an FK constraint cannot be created for this relationship.
346
+
347
+
In practice, this is not a problem as long as the application does not attempt to insert invalid data. For example, if all the data is inserted by EF Core and uses navigations to relate entities, then it is guaranteed that the FK column will contain valid PK values at all times.
348
+
349
+
## Summary and guidance
350
+
351
+
In summary, TPH is usually fine for most applications, and is a good default for a wide range of scenarios, so don't add the complexity of TPC if you don't need it. Specifically, if your code will mostly query for entities of many types, such as writing queries against the base type, then lean towards TPH over TPC.
352
+
353
+
That being said, TPC is also a good mapping strategy to use when your code will mostly query for entities of a single leaf type and your benchmarks show an improvement compared with TPH.
354
+
355
+
Use TPT only if constrained to do so by external factors.
Copy file name to clipboardexpand all lines: entity-framework/core/modeling/keys.md
+1-1
Original file line number
Diff line number
Diff line change
@@ -36,7 +36,7 @@ You can also configure multiple properties to be the key of an entity - this is
36
36
37
37
## Value generation
38
38
39
-
For non-composite numeric and GUID primary keys, EF Core sets up value generation for you by convention. For example, a numeric primary key in SQL Server is automatically set up to be an IDENTITY column. For more information, see [the documentation on value generation](xref:core/modeling/generated-properties).
39
+
For non-composite numeric and GUID primary keys, EF Core sets up value generation for you by convention. For example, a numeric primary key in SQL Server is automatically set up to be an IDENTITY column. For more information, see [the documentation on value generation](xref:core/modeling/generated-properties) and [guidance for specific inheritance mapping strategies](xref:core/modeling/inheritance#key-generation).
Copy file name to clipboardexpand all lines: entity-framework/core/modeling/owned-entities.md
+1-1
Original file line number
Diff line number
Diff line change
@@ -33,7 +33,7 @@ If the `ShippingAddress` property is private in the `Order` type, you can use th
33
33
34
34
The model above is mapped to the following database schema:
35
35
36
-

36
+

37
37
38
38
See the [full sample project](https://github.com/dotnet/EntityFramework.Docs/tree/main/samples/core/Modeling/OwnedEntities) for more context.
> Non-collection navigations can also be marked as required, see [Required one-to-one dependents](xref:core/modeling/relationships#one-to-one) for more information.
151
+
149
152
> [!NOTE]
150
153
> This call cannot be used to create a navigation property. It is only used to configure a navigation property which has been previously created by defining a relationship or from a convention.
0 commit comments