简体   繁体   中英

How can I perform additional DB initialization when using EF (5) Code First Migrations

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 (eg 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.

您可以尝试在派生的DbMigrationConfiguration重写Seed方法(这是自定义数据库初始化程序中原始Seed方法的最接近替代),但请注意,每次迁移数据库时都会执行此方法,因此,您还必须包括以下检查才能创建函数:他们不存在。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM