Making a column sparse with Entity Framework Migrations

I have a database built off code first models, but I want to set some of the columns to sparse. There isn’t a way to this with the fluent api or through annotations. But it can be done with a migration.

There are plenty of articles that show how to run a migration so I will not cover that here.

Instead I’ll just show what you need to add to a new migration, I’m calling the migration MakeAddressSparse, and include the below code.

public partial class MakeAddressSparse: DbMigration
{
   public override void Up()
   {
      Sql("alter table dbo.Address alter column [Address1] varchar(100) sparse null");
      Sql("alter table dbo.Address alter column [Address2] varchar(100) sparse null");
      Sql("alter table dbo.Address alter column [Zipcode] varchar(10) sparse null");
   }

   public override Void Down()
   {
      Sql("alter table dbo.Address alter column [Address1] varchar(100) null");
      Sql("alter table dbo.Address alter column [Address2] varchar(100) null");
      Sql("alter table dbo.Address alter column [Zipcode] varchar(10) null");
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *