简体   繁体   English

更新数据库未使用自定义初始化程序

[英]Update-Database not using custom initialzer

Please do not mistake this SO question as a duplicate: 请不要将此 SO问题当作重复项:

I have the following config for a custom database initializer for code first entity framework: 对于代码优先实体框架的自定义数据库初始化程序,我具有以下配置:

<entityFramework>
  <contexts>
    <context type="MyApp.Context, MyApp">
      <databaseInitializer type="MyApp.CustomInitializer, MyApp" />
    </context>
  </contexts>
</entityFramework>

When I run the application all is well and the InitializeDatabase(Context context) method is called as expected. 当我运行该应用程序时,一切都很好,并按预期调用了InitializeDatabase(Context context)方法。

However, when running the command Update-Database in the Package manager console it is not using my custom initializer. 但是,在程序包管理器控制台中运行命令Update-Database ,它没有使用我的自定义初始化程序。

Why does it work when running the app but not from the package manager console? 为什么在运行应用程序时无法运行,但不能从程序包管理器控制台运行? Which initializer will it be using? 它将使用哪个初始化程序?

If you call Update-Database without specifying where is the ConfigurationType it is assumed that it is in the same assembly. 如果在未指定ConfigurationType的情况下调用Update-Database,则假定它在同一程序集中。 An example : 一个例子 :

Update-Database -ProjectName MyApp.Migrations -ConfigurationTypeName "MyApp.Migrations.MyMigrationConfiguration" -ConnectionString "Data Source=.\SQLEXPRESS;Database=myAppDb;Trusted_Connection=False;User ID=xx;Password=xxxxxx" -ConnectionProviderName "System.Data.SqlClient"

Unfortunately, Update-Database does not use a database initializer at all. 不幸的是, Update-Database根本不使用数据库初始化程序。 It creates a DbMigrator to handle the update (which is also what the MigrateDatabaseToLatestVersion initializer uses), and either tries to find a DbMigrationsConfiguration class or uses one that you provide on the command line. 它创建一个DbMigrator来处理更新(这也是MigrateDatabaseToLatestVersion初始化程序使用的更新),并尝试查找DbMigrationsConfiguration类或使用您在命令行上提供的类。

If you need to do some maintenance after a migration, you can use the Up() function in the migration itself. 如果您需要在迁移后进行一些维护,则可以在迁移本身中使用Up()函数。 Or I suppose you could the Seed() function in your class that overrides DbMigrationsConfiguration (but by default, Seed() runs for every database initialization...however, there are ways to work around this.) 或者我想您可以在您的类中使用Seed()函数来覆盖DbMigrationsConfiguration (但是默认情况下, Seed()每次数据库初始化时运行……但是, 有多种方法可以解决此问题。)

If you want to see it at work: https://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/Migrations/Design/ToolingFacade.cs 如果您想在工作中看到它: https : //entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/Migrations/Design/ToolingFacade.cs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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