Entity Framework 6 - Migrations - Add column with default value and name constraint

1

I want to add a column of type BIT to an existing table with a default value of 1 via migrations. The challenge is ... we have in the company a default for the name of constraints and it is not legal the name automatically created by EF.

Below the code to add the column:

public override void Up()
{    
   AddColumn("dbo.RODADA_DESAFIO", "FL_STATUS", c => c.Boolean(nullable: false, defaultValue: true));
} 

Is there any parameter I can pass in AddColumn to set the name of constraint default or some other way to do this?

I've tried it this way:

public override void Up()
        {
            AddColumn("dbo.RODADA_DESAFIO", "FL_STATUS", c => c.Boolean(nullable: false))
            Sql("ALTER TABLE RODADA_DESAFIO ADD CONSTRAINT DF_RODADADESAFIO_STATUS DEFAULT (1) FOR FL_STATUS");
        }

However, the following error appears:

Column already has a DEFAULT bound to it.
Could not create constraint or index. See previous errors.

NOTE: The column does not yet exist in the database.

    
asked by anonymous 26.05.2017 / 21:02

1 answer

2

Researching a little has found that EF6 does not support default constraints with custom names via the Fluent API. But EF Core yes!

  

Diego Vega (Program Manager, Entity Framework) commented · May 5,   2015 9:05 PM

     

· EF7 beta4 supports this for   relational databases with the DefaultExpression () extension method on   PropertyBuilder. Usage is something like this:

     

modelBuilder.Entity () .Property (p => p.CreatedOn)   .DefaultExpression ("CURRENT_TIMESTAMP");

     

> The EF team does not have plans to back the EF6 feature, but   we could consider a pull request.

Link from the source - https://data.uservoice.com

The solution I found for this question was:

public override void Up()
{
    AddColumn("dbo.RODADA_DESAFIO", "FL_STATUS", c => c.Boolean());
    Sql("UPDATE RODADA_DESAFIO SET FL_STATUS = 1");
    Sql("ALTER TABLE RODADA_DESAFIO ADD CONSTRAINT DF_RODADADESAFIO_STATUS DEFAULT (1) FOR FL_STATUS");
    Sql("ALTER TABLE RODADA_DESAFIO ALTER COLUMN FL_STATUS BIT NOT NULL");
}
  • I added the column, the values will be initially null (for existing lines)
  • Dei update on all lines, set to default value ( BIT 1 / true )
  • I added constraint default with the name I want
  • Now I can change the column to non-nullable without problems
  • 26.05.2017 / 21:52