简体   繁体   English

使用EF(5)代码优先迁移时如何执行附加的数据库初始化

[英]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.

相关问题 使用 EF 代码迁移时,如何更改 model 以设置 SQL 默认日期 - How can I alter a model to set the SQL default date when using EF code migrations 首先使用DB Code时如何更新EF模型? - How to update EF models when using DB Code first? 如何首先使用EF代码重置数据库迁移? - How to reset database migrations using EF code first? EF迁移-如何以及何时迁移数据库 - EF Migrations - How and when is the DB migrated down 使用WebDeploy发布Web应用程序时,如何在DB上自动运行Code First Migrations - How to automatically run Code First Migrations on DB when using WebDeploy to publish web app EF 代码先迁移,DB 生成 GUID 键 - EF code first migrations, DB generated GUID keys 如何通过代码直接使用 EF Core Migrations API - How can I use EF Core Migrations API directly by code 使用Code First EF4.1保存时如何向属性添加默认值? - How can I add default values to a property when saving using Code First EF4.1? 代码优先迁移和初始化错误 - Code First Migrations and initialization error 可以在EF代码中设置第一个迁移种子方法的断点吗? - Can one set a breakpoint in EF code first migrations seed method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM