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:

Why Exceptions Are Slower Than You Think

SQL: Optimizing Multiple WHERE Clauses with Index Intersection

Why Async Controllers Still Block Threads

Post Views: 899

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 *

July 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun    

Most Viewed Posts

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

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes
  • Ajax: Use Axios for HTTP Requests
  • JavaScript: Understand Hoisting
  • HTML: Use Web Storage for Client-Side Data
  • CSS: Use Filter Effects for Visual Magic
  • Windows 11: Unlock God Mode for All Settings

Most Viewed Posts

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

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes

Social

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