Mapping Default Values
Motivation
You may want a certain value as default for a column or a expression to invoke on update, insert and so on.
Static default
cs
builder.Property(x => x.FullName)
.HasDefaultValue("John Smith") // all default value should be `John Smith` in database!
builder.Property(x => x.CreatedDate)
.HasDefaultValue(DateTime.Now); // should be the datetime value when compiled.
1
2
3
4
2
3
4
Dynamic default
Server side
Once again, entity framework core translates the form, so we'll need a sql expression to map the dynamic default.
cs
builder.Property(x => x.CreatedDate)
.HasDefaultValueSql("now()"); // evaluates function `now()` on insert
1
2
2
Client side
Default values can also be generated dynamically from client side with a generator class.
cs
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ValueGeneration;
public class CreatedDateGenerator : ValueGenerator<DateTime>
{
public override DateTime Next(EntityEntry entry)
{
return DateTime.UtcNow; // what value should generate, can be more complex
}
public override bool GeneratesTemporaryValues => false;
}
builder.Property(x => x.CreatedDate)
.HasDefaultValue<CreatedDateGenerator>();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15