1

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 FUNCTION statement must be at the start of a batch.

  • My ALTER DATABASE statement 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.

1 Answer 1

1

You can try to override Seed method in your derived DbMigrationConfiguration (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.

Sign up to request clarification or add additional context in comments.

1 Comment

OK, thanks. And if I have stuff that I need to do per-migration, then I guess I have to figure out a way to determine which migration is being applied, etc. Which seems a lot like re-implementing a lot of what migrations already do. It's such a shame there's no in-built support for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.