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.
- Is it okay to just do that in the OnModelCreating method?
- Can I still take advantage of the AddOrUpdate extension method here?
- 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?
- 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. AddOrUpdate
is mostly for migrations. It has hidden costs (reflection and query to database) so use it carefully.- You can detect it by manually executing SQL query (you cannot use
Database.Exists
insideOnModelCreating
- again because this method is not available when context is being constructed) but it is something that doesn't belong toOnModelCreating
=> 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+
来源:https://stackoverflow.com/questions/9528223/is-it-acceptable-to-put-seed-data-in-the-onmodelcreating-method-in-ef-code-first