Entity Framework 6 - Migrations - Add c column/ default value and name Constraint

Asked

Viewed 325 times

1

I want to add a column like BIT to an existing table with a default value 1 via Migrations. The challenge is...we have in the company a standard for the name of constraints and it is not legal the name created automatically 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 a parameter I can pass in the AddColumn to define the name of constraint default or else some other way to do it?

I tried that 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: Column does not exist yet in the bank.

  • Use the Fluent API.

  • Could you give me an example?

  • This tutorial exemplifies well. http://www.entityframeworktutorial.net/code-first/configure-property-mappings-using-fluent-api.aspx

  • Valeu man, however I did not find anything about default constraints in this tutorial.

1 answer

2


Searching a little I found that EF6 does not support default constraints with custom names via Fluent API. But EF Core does!!!

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 port the Feature to EF6, but we could consider a pull request.

Source link - https://data.uservoice.com

The solution I found to that 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");
}
  1. I added the column, the values will be initially null (for existing lines)
  2. Gave update on all lines, setting to default value (BIT 1 / true)
  3. I added the constraint default with the name I want
  4. Now I can change the column to non-nullable hassle-free

Browser other questions tagged

You are not signed in. Login or sign up in order to post.