MIgrations, Updating a null field to not null

3

I'm updating the phone and CPF field of my User entity that was allowing nulls to non-null. follow the migration file

public partial class Required_fild_users_cpf_phone : DbMigration
{
    public override void Up()
    {
        AlterColumn("dbo.Users", "CPF", c => c.String(nullable: false, maxLength: 11, defaultValue: "00000000000"));
        AlterColumn("dbo.Users", "Phone", c => c.String(nullable: false, maxLength: 13, defaultValue: "02932438029"));
    }

    public override void Down()
    {
        AlterColumn("dbo.Users", "Phone", c => c.String(maxLength: 13));
        AlterColumn("dbo.Users", "CPF", c => c.String(maxLength: 11));
    }
}

Since Migrations complains that my table has data and some of the records I have to update are null (empty) then I have to generate a migration file that updates the null fields to a default value so that migration does not errors, but I would like to be in the file itself

    
asked by anonymous 01.12.2017 / 14:38

1 answer

3

Add an update to your Up() by setting the CPF to empty when it is null, but before AlterColumn .

    public override void Up()
    {
        Sql("update dbo.Users set CPF = '' where CPF is null");
        AlterColumn("dbo.Users", "CPF", c => c.String(nullable: false, maxLength: 11, defaultValue: "00000000000"));
        AlterColumn("dbo.Users", "Phone", c => c.String(nullable: false, maxLength: 13, defaultValue: "02932438029"));
    }
    
01.12.2017 / 14:41