Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 495
Chev Avatar asked Mar 02 '12 05:03

Chev


2 Answers

  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.
like image 128
Ladislav Mrnka Avatar answered Oct 27 '22 01:10

Ladislav Mrnka


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+

like image 39
evermeire Avatar answered Oct 26 '22 23:10

evermeire