dotnet / dotnet/efcore

Extensibility for getting the default column value for a type mapping (for adding non-nullable columns)

Open
#34,790 0 comments 2 reactions 0 assignees View on GitHub
area-migrations area-type-mapping
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

When adding a non-nullable column to an existing table, a default value must be provided, otherwise the ALTER TABLE fails. We have various hard-coded hacks to deal with this scenario: [MigrationsModelDiffer.GetDefaultValue()](https://github.com/dotnet/efcore/blob/main/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs#L2529) has specific handling for strings and arrays, and returns the default CLR value otherwise:

```c#
protected virtual object? GetDefaultValue(Type type)
=> type == typeof(string)
? string.Empty
: type.IsArray
? Array.CreateInstance(type.GetElementType()!, 0)
: type.UnwrapNullableType().GetDefaultValue();
```

This is wrong for reference types such as `List` and probably NetTopologySuite things as well.

We also have hacky differ code [here](https://github.com/dotnet/efcore/blob/main/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs#L1253), which specifically identifies `CollectionToJsonStringConverter` to set `[]` for JSON columns.

I think we simply need a hook on our type mapping which provides this.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.