I’m moving my ef-code-first application to the code-first-migrations model, and switching my database initializer from DropCreateDatabaseIfModelChanges to MigrateDatabaseToLatestVersion.
In my original initializer, I was creating some user-defined functions, etc. and making changes to the database configuration (e.g. SET AUTO_CLOSE OFF). All of that stuff was achieved by executing SQL directly against the DB, since it’s not supported via EF.
Now that I’ve moved over to the migrations model, I’m attempting to do much the same, by adding code to the Up method of the generated DbMigration class. This code uses the Sql method to inject SQL.
However, I’m getting various errors as a result, such as:
-
My SQL to create the user-defined functions cause an error saying that the
CREATE FUNCTIONstatement must be at the start of a batch. -
My
ALTER DATABASEstatement causes an error saying that it cannot be used inside a user transaction. (I don’t create a transaction, but presumably there is one already started).
How can I overcome this? In the DbMigration-derived class, I don’t seem to have access to a DbContext, so I can’t get at the database directly.
You can try to override
Seedmethod in your derivedDbMigrationConfiguration(that is the closest replacement for original Seed method in custom database initializer) but beware that this method is executed every time the database is migrated so you must also include checks to create functions only if they don’t exists.