Empty data (NULLs) will destroy your C# application with NullReferenceException errors. Therefore, you must rigorously enforce which columns in your database are allowed to be empty, and establish smart default values when data is omitted during an insert.
Starting with C# 8, Microsoft introduced "Nullable Reference Types." EF Core is incredibly smart and reads this compiler setting to configure your SQL tables.
public class Customer
{
public int Id { get; set; }
// NON-NULLABLE: EF Core makes the SQL column "NOT NULL"
public string Name { get; set; } = string.Empty;
// NULLABLE (Notice the '?'): EF Core makes the SQL column "NULL"
public string? MiddleName { get; set; }
}
<Nullable>disable</Nullable> in its .csproj file, EF Core will assume ALL strings are nullable by default. In that case, you MUST use the Fluent API IsRequired() or the [Required] Data Annotation to enforce NOT NULL constraints.
When a record is created, there are certain fields (like a timestamp) that you don't want the C# code to manage. You want the database engine itself to generate the value natively.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>(entity =>
{
// Example: If a customer is inserted without a status, SQL Server forces 'Active'
entity.Property(c => c.Status)
.HasDefaultValue("Active");
// Example: SQL Server natively executes GETUTCDATE() when the row is created
entity.Property(c => c.CreatedOn)
.HasDefaultValueSql("GETUTCDATE()");
});
}
EF Core allows you to specify exactly when a value is generated (On Add, On Update, or Never).
// This column is generated by SQL Server every time the record is modified!
entity.Property(c => c.LastModifiedOn)
.ValueGeneratedOnUpdate()
.HasDefaultValueSql("GETUTCDATE()");
Q: "We mapped a default value using `.HasDefaultValueSql('GETDATE()')`. However, in our C# code, we explicitly instantiated a new entity `var user = new User { CreatedDate = new DateTime(2000, 1, 1) };` and saved it. Will SQL Server overwrite our year 2000 date with the current GETDATE()?"
Architect Answer: "No, SQL Server will respect the explicitly provided C# date (Year 2000). A database Default Value Constraint only triggers if the INSERT statement completely omits the column. Because you explicitly defined the `CreatedDate` in C#, EF Core includes that explicit date in the `INSERT` statement. The only way SQL Server will trigger the `GETDATE()` default is if EF Core excludes the column from the INSERT statement, which happens when the C# property is left completely unassigned (or matches its native CLR default, like `DateTime.MinValue`)."