Entity Framework Core Mastery

Required Properties & Database Defaults

1 Views Updated 5/4/2026

Required Properties & Database Defaults

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.

1. Nullability in C# vs SQL Server

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; }
}
Legacy Note: If your project has <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.

2. Applying Database Defaults (Fluent API)

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()");
    });
}

3. Value Generation Strategies

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()");

4. Interview Mastery

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

Entity Framework Core Mastery
1. Foundations & Architecture
Introduction to Object Relational Mapping (ORM) Entity Framework Core Architecture & Providers Setup and DbContext Integration Code-First vs Database-First Approaches Reverse Engineering Existing Databases (Scaffolding)
2. Code-First Modeling
Entity Conventions & Data Annotations The Fluent API Deep Dive (OnModelCreating) Primary Keys, Composite Keys, & Guids Required Properties & Database Defaults Value Conversions (Enums & Strongly Typed IDs)
3. Relational Architecture
One-to-Many Relationships & Foreign Keys One-to-One Relationships (Dependent Entities) Many-to-Many Relationships & Navigation Properties Owned Entity Types (Value Objects) Table-per-Hierarchy (TPH) Inheritance
4. Data Querying & LINQ
Basic LINQ Queries & IQueryable Execution Tracking vs No-Tracking Queries (Performance) Eager Loading vs Explicit Loading (Include) Lazy Loading Pitfalls & Proxies Client vs Server Evaluation Parsing
5. Manipulating Data (CUD)
Adding, Updating, and Removing Entities The ChangeTracker and Entity States Disconnected Entities in Web APIs Batch Updates and Deletes (.NET 7+)
6. Advanced Performance & Scale
Concurrency Tokens and Optimistic Locking Raw SQL Queries and Views (FromSqlRaw) Compiled Queries for High Throughput Interceptors (Logging & Auditing Data Changes) DbContext Pooling Mechanisms Managing Complex EF Core Migrations (CI/CD)