Default value for Required fields in Entity Framework migrations?

In addition to the answer from @webdeveloper and @Pushpendra, you need to manually add updates to your migration to update existing rows. For example:

public override void Up()
{
    Sql("UPDATE [dbo].[Movies] SET Title="No Title" WHERE Title IS NULL");
    AlterColumn("dbo.Movies", "Title", c => c.String(nullable: false,defaultValue:"MyTitle"));
}

This is because AlterColumn produces DDL to set the default of the column to some specific value in the table specification. The DDL does not affect existing rows in the database.

You’re actually making two changes at the same time (setting the default and making the column NOT NULL) and each of them is valid individually, but since you’re making the two at the same time, you can expect the system to ‘intelligently’ realize your intent and set all NULL values to the default value, but this is not what’s expected all the time.

Suppose you’re only setting the default value for the column, and not making it NOT NULL. You obviously don’t expect all the NULL records to be updated with the default you provide.

So, in my opinion, this is not a bug, and I don’t want EF to update my data in the ways that I don’t explicitly tell it to do. The developer is responsible to instruct the system about what to do with the data.

Leave a Comment