Is it acceptable to put seed data in the OnModelCreating method in EF code-first?

社会主义新天地 提交于 2019-12-07 07:57:12

问题


I know how to do seed data with the migrations API in EF 4.3. I've been playing with that all night. However, my ultimate goal is to get my project to the point where a user can pull it from source control and press F5 and they are good to go, database, seed data, and all.

Currently code-first does an excellent job of building the DB on a fresh build but seed data isn't inserted until I do Update-Database in the package manager console. At that point it runs the seed method and inserts my seed data.

  1. Is it okay to just do that in the OnModelCreating method?
  2. Can I still take advantage of the AddOrUpdate extension method here?
  3. Will this seed data be run every time I press F5? If so, can I detect if the DB has already been created or not and only add this seed data on initial database creation?

回答1:


  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.



回答2:


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+



来源:https://stackoverflow.com/questions/9528223/is-it-acceptable-to-put-seed-data-in-the-onmodelcreating-method-in-ef-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!