Entity Framework Core Interview Question #89
How do you configure default values in EF Core?
Migrations, Database Schema & Data Management Mid-Level Intermediate
Quick Interview Answer
A property can be configured with a database default value or default SQL expression. The database uses the default when an INSERT does not provide a value for that column according to the mapping.
Detailed Explanation
A property can be configured with a database default value or default SQL expression. The database uses the default when an INSERT does not provide a value for that column according to the mapping.
Database defaults are useful when the rule should be enforced independently of the application process. Application-side defaults can also be appropriate when the value is part of domain construction.
Be clear about which layer owns the default so values are predictable across all data-writing paths.
Code Example
modelBuilder.Entity<Order>()
.Property(o => o.CreatedAtUtc)
.HasDefaultValueSql("SYSUTCDATETIME()");
modelBuilder.Entity<Product>()
.Property(p => p.IsPublished)
.HasDefaultValue(false);