Entity Framework Code First From Database Perform Migration to change attributes of a field specified as `bit` in database

101 views Asked by At

I am using Entity Code First from Data Base. This is my user model.

    public partial class User
    {
      //other fields
      [Required]
      [MaxLength(15)]
      public string Passkey { get; set; }
      [Required]
      public bool isAdmin { get; set; }  
    }

The code below was generated when I wanted to change the Passkey column in Users table from varbinary to varchar, which i did by changing the type from byte to string in the model as public string Passkey { get; set; } (this is the changed form). I was able to update the datatype.

public partial class AddPasskey : DbMigration
        {
            public override void Up()
            {
                AlterColumn("dbo.Users", "Passkey", c => c.String(nullable: false, maxLength: 15));
            }

            public override void Down()
            {
                AlterColumn("dbo.Users", "Passkey", c => c.Binary(nullable: false, maxLength: 15));
            }
        }

I have this 'isAdmin' property set as required. I want to remove this required validation, and set its default value to 0. I copied the code that was auto-generated for migration for Passkey and changed it. Below is the changed code, which is wrong.

    public partial class AddisAdmin : DbMigration
        {
            public override void Up()
            {
                AlterColumn("dbo.Users", "isAdmin", c => c.bool(nullable: false, defaultValue:0));
            }

            public override void Down()
            {
                AlterColumn("dbo.Users", "isAdmin", c => c.bool(nullable: false));
            }
        }

How do I perform this migration? What is the correct syntax for updating a field specified as bit in database?

3

There are 3 answers

2
Stuart On

You need to Enable-Migrations first, this will generate a Migrations directory, you may have done this already.

After configuring your migration(s) you can then run then by running Update-Database.

I run the above commands from the "Package Manager Console", in Tools menu.

Also, to change the data type, you can also run SQL via the Sql() method:

Sql("ALTER TABLE dbo.Users ALTER COLUMN isAdmin BIT")

0
Huske On

First of all, define you model type as nulable using bool? syntax or Nullable<bool>. Anything that is not nullable in your code cannot be optional in the database. So, make it nullable and remove [Required] data annotation from your model above isAdmin property.

0
Haitham Shaddad On

Remove the code you added manually and run the add-migration command again to add a new migration and a new file should be created with the change required, there you can alter it and set the default value to zero