我知道如何使用EF 4.3中的迁移API进行种子数据。我整夜都在玩。但是,我的最终目标是将我的项目从源控制中从源代码控制拉出并按下F5,并且它们是好的,数据库,种子数据和所有。

目前代码首先做出了在新建构建中构建DB的优秀工作,但在Package Manager控制台中的更新数据库之前未插入种子数据。此时它运行种子方法并插入我的种子数据。

  1. 在onmodelcreating方法中可以做到这一点吗?
  2. 我仍然可以利用这里的addorupdate扩展方法吗?
  3. 每次按F5都会运行此种子数据吗?如果是这样,我可以检测DB是否已经创建或不创建,并且仅在初始数据库创建时添加此种子数据?
有帮助吗?

解决方案

  1. No. OnModelCreating is executed every time the model definition must be built = every time you start the application and use data access for the first time. It may be nice in your development environment but it is not nice in production. Moreover you cannot use context while it is constructed so the only way how to seed data in this method is using SQL directly.
  2. AddOrUpdate is mostly for migrations. It has hidden costs (reflection and query to database) so use it carefully.
  3. You can detect it by manually executing SQL query (you cannot use Database.Exists inside OnModelCreating - again because this method is not available when context is being constructed) but it is something that doesn't belong to OnModelCreating => single responsibility pattern.

There are better ways how to do this.

  • MigrateDatabaseToLatestVersion database initializer in EF 4.3 will run your migration set if database doesn't exist or update existing database
  • You can use DbMigrator class at bootstrap of your application and migrate your database to the last version with the higher control over whole process
  • I didn't check if it is possible but you should be able to modify MSBuild or add pre build action to your project which will either somehow use power shell commands or execute custom console application using DbMigrator class.

其他提示

What is wrong with seeding data in the overridden Seed() method when inheriting from CreateDatabaseIfNotExists class?

It worked with EF 4.2 and below and seems to still be working with EF 4.3+

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top