Tag Archives: Code first

Creating a custom migration operation in Entity Framework

Since the release of Entity Framework 6.0 it became possible to create custom migration operations enabling us to make operations similar to the CreateTable and DropTable functions. This way we can encapsulate more database definitions such as adding a Check constraint or a description to a column (or any other object).

Of course we had means to do this before version 6.0 as well using the Sql function of the DbMigration which looked like this:

Sql("ALTER TABLE [Products] ADD CONSTRAINT [CK_Products_SKU] " +
    "CHECK (SKU LIKE '[A-Z][A-Z]-[0-9][0-9]%')");

Creating a migration operation is however a big improvement over using the Sql function in the migration step and executing the SQL statement that was passed in regardless what database is used. Thus the code we get using custom migration operations not only looks better but it is database agnostic as well.
Continue reading