I am using EF code first for my project. I have following code in my DataModel
[HiddenInput(DisplayValue = false)]
public DateTime? PasswordDate { get; set; }
To make this non-nullable I removed '?' and ran Add-Migration command from Package manager console. following migration file was generated.
public partial class PasswordDate : DbMigration
{
public override void Up()
{
AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime(nullable: false));
}
public override void Down()
{
AlterColumn("dbo.CertificateInfoes", "PasswordDate", c => c.DateTime());
}
}
But when I run Update-Database command:
Update-Database -SourceMigration 201309020721215_PasswordDate
I get following error: Cannot insert the value NULL into column 'PasswordDate', table ''; column does not allow nulls. UPDATE fails. The statement has been terminated.
Kindly suggest the solutions.
That's because you allowed NULL
values in that column, then tried to make it non-nullable. It will subsequently try to migrate your existing data into that newly non-nullable column, which will break because you already have NULL
values in there.
Two solutions:
1) Change it back to nullable
2) Give it a default value for items that don't have a value.