[英]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
. 我将ef-code-first应用程序移至code-first-migrations模型,并将数据库初始化程序从DropCreateDatabaseIfModelChanges
切换到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
). 在我最初的初始化程序中,我正在创建一些用户定义的函数等,并对数据库配置进行更改(例如SET AUTO_CLOSE OFF
)。 All of that stuff was achieved by executing SQL directly against the DB, since it's not supported via EF. 所有这些工作都是通过直接对数据库执行SQL来实现的,因为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. 现在,我已经转移到迁移模型,我试图通过将代码添加到生成的DbMigration
类的Up
方法中来做很多DbMigration
。 This code uses the Sql
method to inject SQL. 此代码使用Sql
方法来注入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. 我创建用户定义函数的SQL导致错误,指出CREATE FUNCTION
语句必须在批处理的开始。
My ALTER DATABASE
statement causes an error saying that it cannot be used inside a user transaction. 我的ALTER DATABASE
语句导致一个错误,表明它不能在用户事务内使用。 (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. 在DbMigration
派生的类中,我似乎没有访问DbContext的权限,因此无法直接访问数据库。
您可以尝试在派生的DbMigrationConfiguration
重写Seed
方法(这是自定义数据库初始化程序中原始Seed方法的最接近替代),但请注意,每次迁移数据库时都会执行此方法,因此,您还必须包括以下检查才能创建函数:他们不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.