I'm trying to use CF to build a model for an existing database. I have a column in which I forgot to set a sane default value. And rather than compromise the purity of the initial migration by changing it, I just figured I'd create another migration (that's what migrations are for, right? :)
public override void Up()
{
AlterColumn("Config", "DefaultTaxPerDollar", c => c.Decimal(nullable: false, precision: 19, scale: 5, defaultValue: 0.087m));
}
public override void Down()
{
AlterColumn("Config", "DefaultTaxPerDollar", c => c.Decimal(nullable: false, precision: 19, scale: 5, defaultValue: 0.0m));
}
But this produces Column already has a DEFAULT bound to it.
error from the SQL Server.
How does one change a default value using CF migrations? Or, how does one simply remove a default value (and subsequently re-create it with a different value)?
Edit:
Here is the SQL generated:
ALTER TABLE [Config] ADD CONSTRAINT DF_DefaultTaxPerDollar DEFAULT 0.087 FOR [DefaultTaxPerDollar]
ALTER TABLE [Config] ALTER COLUMN [DefaultTaxPerDollar] [decimal](19, 5) NOT NULL
I think I may have found a solution, to use the Sql()
method with some complex SQL inspired by this post. The problem stems from the fact that SQL Server uses constraints to implement defaults (OH! how I miss MySQL!) with a generated name for the constraint. So the Code First team could not simply change or remove/re-create the default value easily.
Removal of default constraints inspired by reverse migrations produced by Entity Framework for SQL Server
It's slightly shorter, but the usage is the same.
The Guid is used to make a unique variable name in case you are going to drop several constraints in one migration.
Here's a solution that was inspired by this post. It's not exactly an elegant method, but it works for me.
And in your migration, you can call it like this:
The reason for using the lamba is because you have to make three distinct calls to
Sql()
. I was never able to get this to work as one long query - tried many combinations of the keywordGO
in many different places. I also tried reversing the logic on the first query so that the UDF only gets recreated if it does not exist, and it didn't work. I suppose recreating it every time is more robust anyway.