Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
ASP.Net MVC / ASP.Net WebForms / C# / SQL

How to add default value for Entity Framework migrations for DateTime and Bool

- 19.06.22 | 16.01.26 - ErcanOPAK
When working with Code First Migrations, developers often struggle with setting default values at the database level. While you can set a default value in your C# class, doing it directly in the SQL schema is much more robust. Here is how you can achieve this using defaultValue and defaultValueSql.

1. Using Static Default Values

For simple types like Booleans or Integers, you can use the defaultValue parameter inside your migration file. This tells SQL Server to assign this value automatically when a new row is inserted.

public override void Up()
{
    CreateTable(
        "dbo.SimpleEntities",
        c => new
            {
                id = c.Long(nullable: false, identity: true),
                name = c.String(),
                deleted = c.Boolean(nullable: false, defaultValue: true), // Set default to true
            })
        .PrimaryKey(t => t.id);
}

After running update-database -verbose, you’ll see that EF generates a SQL query containing the DEFAULT constraint. The resulting table definition will look like this:

CREATE TABLE [dbo].[SimpleEntities] (
    [id]      BIGINT         IDENTITY (1, 1) NOT NULL,
    [name]    NVARCHAR (MAX) NULL,
    [deleted] BIT            DEFAULT ((1)) NOT NULL, -- Database level default
    CONSTRAINT [PK_dbo.SimpleEntities] PRIMARY KEY CLUSTERED ([id] ASC)
);

2. Using Dynamic SQL Values (e.g., GETDATE)

If you need a dynamic value like the current timestamp, defaultValue won’t work because it’s a C# parameter. Instead, you must use defaultValueSql to pass a raw SQL function.

public override void Up()
{
    CreateTable("dbo.Users",
        c => new
            {
                ID = c.Int(nullable: false, identity: true),
                Created = c.DateTime(nullable: false, defaultValueSql: "GETDATE()"),
            })
        .PrimaryKey(t => t.ID);
}

💡 Why use defaultValueSql?

It ensures that the time is generated by the Database Server, not the Application Server. This prevents issues with different time zones or unsynchronized clocks between your web server and database.

⚡ Quick Tip: If you are modifying an existing column instead of creating a new table, use the AlterColumn method with the same parameters!

Related posts:

Convert a Comma-Delimited List to a Table in SQL

SQL: Use CTEs (WITH Clause) for Readable Complex Queries

C#: Simplifying Initialization with ??= Operator

Post Views: 858

Post navigation

String Interpolation, String Format, String Concat and String Builder in C#
How to get stored procedure parameters details in SQL

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (858)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • Find numbers with more than two decimal places in SQL (448)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (858)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com