Migrations, Updating a null field to not null

Asked

Viewed 179 times

3

I am updating the phone field and CPF of my User entity that was allowing nulls to not nulls. 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));
    }
}

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

1 answer

3


Add to your Up() an update setting the CPF to empty when it is null, but before the 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"));
    }
  • I also tried but nothing works, I did a test and it works when we are creating the field. thanks

  • You could put in response the output message with the error that appears?

  • Hi Amigo, it worked when I did a migration by did. first the CPF and then the PHONE.

Browser other questions tagged

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