Adding ROWGUIDCOL to Entity Framework Code First using migrations

To add add a ROWGUIDCOL to a unique identifier in a table using code first you have to use code migrations.

Below is the snippet you need. I haven’t covered how to perform a migration because there are plenty of articles available.

public partial class AddRowGuidCol : DbMigration
{
   public override void Up()
   {
      Sql("ALTER TABLE dbo.Address ALTER COLUMN [AddressID] ADD ROWGUIDCOL");
   }

   public override Void Down()
   {
      Sql("ALTER TABLE dbo.Address ALTER COLUMN [AddressID] DROP ROWGUIDCOL");
   }
}

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");
   }
}