Search code examples
entity-frameworkentity-framework-6entity-framework-6.1

How is a database schema change applied in entity framework using code first without migrations


I do not want to use migrations at the moment but code first.

When I use the modelbuilder and the Fluent API to create a new table with database properties.

How do I say "apply changes now". Are the changes executed when the first query hits the database? Or is there any other better approach?


Solution

  • There are multiple Database Initializers at your disposal. Which one you choose to use will vary depending on your overall development goals.

    The MigrateDatabaseToLatestVersion initializer is the most flexible of your options, offering you the ability to incrementally add to your model. This "Migration" process is also sometimes referred to as "Data Motion".

    Another option available to you is CreateDatabaseIfNotExists, which is the Default strategy. In this strategy, the first time you access any class which requires database access, the database will be created if it doesn't exist. If the database already exists, nothing will happen. If the schema of the database does not match the model, the transaction will fail and an error will be thrown.

    Another popular initializer is DropCreateDatabaseIfModelChanges. This is an implementation of IDatabaseInitializer that will DELETE, recreate, and optionally re-seed the database only if the model has changed since the database was created.

    Lastly, you have DropCreateDatabaseAlways. As you may expect, this is an implementation of IDatabaseInitializer that will always recreate and optionally re-seed the database the first time that a context is used in the app domain.