Skip to content

Commit

Permalink
Improvements to the value generation page
Browse files Browse the repository at this point in the history
Fixes #2980
Fixes #2947
  • Loading branch information
roji committed Jan 10, 2021
1 parent ae420d9 commit 9bf7100
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 54 deletions.
120 changes: 68 additions & 52 deletions entity-framework/core/modeling/generated-properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,42 @@ uid: core/modeling/generated-properties

# Generated Values

## Value generation patterns
Database columns can have their values generated in various ways: primary key columns are frequently auto-incrementing integers, other columns have default or computed values, etc. This page details various patterns for configuration value generation with EF Core.

There are three value generation patterns that can be used for properties:
## Default values

* No value generation
* Value generated on add
* Value generated on add or update
On relational databases, a column can be configured with a default value; if a row is inserted without a value for that column, the default value will be used.

### No value generation
You can configure a default value on a property:

No value generation means that you will always supply a valid value to be saved to the database. This valid value must be assigned to new entities before they are added to the context.
[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/DefaultValue.cs?name=DefaultValue&highlight=5)]

### Value generated on add
You can also specify a SQL fragment that is used to calculate the default value:

Value generated on add means that a value is generated for new entities.
[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/DefaultValueSql.cs?name=DefaultValueSql&highlight=5)]

Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during `SaveChanges()`.
## Computed columns

If you add an entity to the context that has a value assigned to the property, then EF will attempt to insert that value rather than generating a new one. A property is considered to have a value assigned if it is not assigned the CLR default value (`null` for `string`, `0` for `int`, `Guid.Empty` for `Guid`, etc.). For more information, see [Explicit values for generated properties](xref:core/saving/explicit-values-generated-properties).
On most relational databases, a column can be configured to have its value computed in the database, typically with an expression referring to other columns:

> [!WARNING]
> How the value is generated for added entities will depend on the database provider being used. Database providers may automatically set up value generation for some property types, but others may require you to manually set up how the value is generated.
>
> For example, when using SQL Server, values will be automatically generated for `GUID` properties (using the SQL Server sequential GUID algorithm). However, if you specify that a `DateTime` property is generated on add, then you must set up a way for the values to be generated. One way to do this, is to configure a default value of `GETDATE()`, see [Default Values](#default-values).
[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/ComputedColumn.cs?name=DefaultComputedColumn&highlight=3)]

### Value generated on add or update
The above creates a *virtual* computed column, whose value is computed every time it is fetched from the database. You may also specify that a computed column be *stored* (sometimes called *persisted*), meaning that it is computed on every update of the row, and is stored on disk alongside regular columns:

Value generated on add or update means that a new value is generated every time the record is saved (insert or update).
[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/ComputedColumn.cs?name=StoredComputedColumn&highlight=3)]

Like `value generated on add`, if you specify a value for the property on a newly added instance of an entity, that value will be inserted rather than a value being generated. It is also possible to set an explicit value when updating. For more information, see [Explicit values for generated properties](xref:core/saving/explicit-values-generated-properties).
> [!NOTE]
> Support for creating stored computed columns was added in EF Core 5.0.
> [!WARNING]
> How the value is generated for added and updated entities will depend on the database provider being used. Database providers may automatically set up value generation for some property types, while others will require you to manually set up how the value is generated.
>
> For example, when using SQL Server, `byte[]` properties that are set as generated on add or update and marked as concurrency tokens, will be set up with the `rowversion` data type - so that values will be generated in the database. However, if you specify that a `DateTime` property is generated on add or update, then you must set up a way for the values to be generated. One way to do this, is to configure a default value of `GETDATE()` (see [Default Values](#default-values)) to generate values for new rows. You could then use a database trigger to generate values during updates (such as the following example trigger).
>
> [!code-sql[Main](../../../samples/core/Modeling/FluentAPI/ValueGeneratedOnAddOrUpdate.sql)]
## Primary keys

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.

## Value generated on add
For more information, [see the documentation about keys](xref:core/modeling/keys).

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.
## Explicitly configuring value generation

You can configure any property to have its value generated for inserted entities as follows:
We saw above that EF Core automatically sets up value generation for primary keys - but we may want to do the same for non-key properties. You can configure any property to have its value generated for inserted entities as follows:

### [Data Annotations](#tab/data-annotations)

Expand All @@ -62,54 +55,77 @@ You can configure any property to have its value generated for inserted entities

***

> [!WARNING]
> This just lets EF know that values are generated for added entities, it does not guarantee that EF will set up the actual mechanism to generate values. See [Value generated on add](#value-generated-on-add) section for more details.
Similarly, a property can be configured to have its value generated on add or update:

### Default values
### [Data Annotations](#tab/data-annotations)

On relational databases, a column can be configured with a default value; if a row is inserted without a value for that column, the default value will be used.
[!code-csharp[Main](../../../samples/core/Modeling/DataAnnotations/ValueGeneratedOnAddOrUpdate.cs?name=ValueGeneratedOnAddOrUpdate&highlight=5)]

You can configure a default value on a property:
### [Fluent API](#tab/fluent-api)

[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/DefaultValue.cs?name=DefaultValue&highlight=5)]
[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/ValueGeneratedOnAddOrUpdate.cs?name=ValueGeneratedOnAddOrUpdate&highlight=5)]

You can also specify a SQL fragment that is used to calculate the default value:
***

[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/DefaultValueSql.cs?name=DefaultValueSql&highlight=5)]
> [!WARNING]
> Unlike with default values or computed columns, we are not specifying *how* the values are to be generated; that depends on the database provider being used. Database providers may automatically set up value generation for some property types, but others may require you to manually set up how the value is generated.
>
> For example, on SQL Server, when a Guid property is configured as value generated on add, the provider automatically performs value generation client-side, using an algorithm to generate optimal sequential GUID values. However, specifying `ValueGeneratedOnAdd()` on a DateTime property will have no effect ([see the section below for DateTime value generation](#date-time-value-generation)).
>
> Similarly, byte[] properties that are configured as generated on add or update and marked as concurrency tokens are set up with the rowversion data type, so that values are automatically generated in the database. However, specifying `ValueGeneratedOnAddOrUpdate()` will again have no effect.
>
> [!NOTE]
> Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during `SaveChanges()`.
Specifying a default value will implicitly configure the property as value generated on add.
## Date/time value generation

## Value generated on add or update
A common request is to have a database column which contains the date/time for when the column was first inserted (value generated on add), or for when it was last updated (value generated on add or update). As there are various strategies to do this, EF Core providers usually don't set up value generation automatically for date/time columns - you have to configure this yourself.

### [Data Annotations](#tab/data-annotations)
### Creation timestamp

[!code-csharp[Main](../../../samples/core/Modeling/DataAnnotations/ValueGeneratedOnAddOrUpdate.cs?name=ValueGeneratedOnAddOrUpdate&highlight=5)]
Configuring a date/time column to have the creation timestamp of the row is usually a matter of configuring a default value with the appropriate SQL function. For example, on SQL Server you may use the following:

### [Fluent API](#tab/fluent-api)
[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/DefaultValueSql.cs?name=DefaultValueSql&highlight=5)]

[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/ValueGeneratedOnAddOrUpdate.cs?name=ValueGeneratedOnAddOrUpdate&highlight=5)]
Be sure to select the appropriate function, as several may exist (e.g. `GETDATE()` vs. `GETUTCDATE()`).

***
### Update timestamp

> [!WARNING]
> This just lets EF know that values are generated for added or updated entities, it does not guarantee that EF will set up the actual mechanism to generate values. See [Value generated on add or update](#value-generated-on-add-or-update) section for more details.
Although stored computed columns seem like a good solution for managing last-updated timestamps, databases usually don't allow specifying functions such as `GETDATE()` in a computed column. As an alternative, you can set up a database trigger to achieve the same effect:

### Computed columns
```sql
CREATE TRIGGER [dbo].[Blogs_UPDATE] ON [dbo].[Blogs]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;

On most relational databases, a column can be configured to have its value computed in the database, typically with an expression referring to other columns:
IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;

[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/ComputedColumn.cs?name=DefaultComputedColumn)]
DECLARE @Id INT

The above creates a *virtual* computed column, whose value is computed every time it is fetched from the database. You may also specify that a computed column be *stored* (sometimes called *persisted*), meaning that it is computed on every update of the row, and is stored on disk alongside regular columns:
SELECT @Id = INSERTED.BlogId
FROM INSERTED

[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/ComputedColumn.cs?name=StoredComputedColumn)]
UPDATE dbo.Blogs
SET LastUpdated = GETDATE()
WHERE BlogId = @Id
END
```

> [!NOTE]
> Support for creating stored computed columns was added in EF Core 5.0.
For information on creating triggers, [see the documentation on using raw SQL in migrations](xref:core/managing-schemas/migrations/managing#adding-raw-sql).

## Overriding values

If you add an entity to the context that has a value assigned to the property, then EF will attempt to insert that value rather than generating a new one. A property is considered to have a value assigned if it is not assigned the CLR default value (`null` for `string`, `0` for `int`, `Guid.Empty` for `Guid`, etc.).

For more information, see [Explicit values for generated properties](xref:core/saving/explicit-values-generated-properties).

## No value generation

Disabling value generation on a property is typically necessary if a convention configures it for value generation. For example, if you have a primary key of type int, it will be implicitly set configured as value generated on add; you can disable this via the following:
Apart from specific scenarios such as those described above, properties typically have no value generation configured; this means that it's up to the application to always supply a value to be saved to the database. This value must be assigned to new entities before they are added to the context.

However, in some cases you may want to disable value generation that has been set up by convention. For example, a primary key of type int is usually implicitly configured as value-generated-on-add (e.g. identity column on SQL Server). You can disable this via the following:

### [Data Annotations](#tab/data-annotations)

Expand Down
10 changes: 8 additions & 2 deletions entity-framework/core/modeling/keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ uid: core/modeling/keys

A key serves as a unique identifier for each entity instance. Most entities in EF have a single key, which maps to the concept of a *primary key* in relational databases (for entities without keys, see [Keyless entities](xref:core/modeling/keyless-entity-types)). Entities can have additional keys beyond the primary key (see [Alternate Keys](#alternate-keys) for more information).

## Configuring a primary key

By convention, a property named `Id` or `<type name>Id` will be configured as the primary key of an entity.

[!code-csharp[Main](../../../samples/core/Modeling/Conventions/KeyId.cs?name=KeyId&highlight=3,11)]
Expand All @@ -18,11 +20,11 @@ By convention, a property named `Id` or `<type name>Id` will be configured as th
You can configure a single property to be the primary key of an entity as follows:

## [Data Annotations](#tab/data-annotations)
### [Data Annotations](#tab/data-annotations)

[!code-csharp[Main](../../../samples/core/Modeling/DataAnnotations/KeySingle.cs?name=KeySingle&highlight=3)]

## [Fluent API](#tab/fluent-api)
### [Fluent API](#tab/fluent-api)

[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/KeySingle.cs?name=KeySingle&highlight=4)]

Expand All @@ -32,6 +34,10 @@ You can also configure multiple properties to be the key of an entity - this is

[!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/KeyComposite.cs?name=KeyComposite&highlight=4)]

## Value generation

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

## Primary key name

By convention, on relational databases primary keys are created with the name `PK_<type name>`. You can configure the name of the primary key constraint as follows:
Expand Down

0 comments on commit 9bf7100

Please sign in to comment.