-
Notifications
You must be signed in to change notification settings - Fork 224
Migrations
The generator is designed to reverse-engineer an existing database. If you want to use EF migrations going forward after the initial reverse-engineering, this page explains the transition.
Set Settings.GenerateSeparateFiles = true in Database.tt and save to generate the entity classes and configuration.
Run in the Package Manager Console or .NET CLI:
# Package Manager Console
Add-Migration Init
Update-Database
# .NET CLI
dotnet ef migrations add Init
dotnet ef database updateIf EF Core detects differences between the model and your existing database, the migration script will contain those changes. Review it carefully and ensure it is empty (no changes) before running Update-Database, since your database already has the schema:
# Create an empty migration that assumes the database is already in sync
Add-Migration Init -IgnoreChanges # EF 6 only
# For EF Core, create the migration, then manually empty the Up() and Down() methods before applyingOnce migrations are set up, delete the Database.tt and EF.Reverse.POCO.v3.ttinclude files. Inform your DBAs that the schema is now managed via code-first migrations.
Set Settings.GenerateSeparateFiles = true in Database.tt and save.
Enable-MigrationsAdd-Migration Init -IgnoreChangesThis creates an empty initial migration that assumes the current database schema is already in sync with the generated model.
Delete the Database.tt and .ttinclude files. Schema changes are now managed via migrations.
If your DBAs manage the database schema (rather than developers), this is the recommended workflow:
- DBAs apply schema changes to the production database via SQL scripts or patches.
- Developers apply the same patches to their local development databases.
- After patching, developers re-save
Database.ttto regenerate the entity model. - Generated changes are committed and pushed.
This approach keeps the generated code in source control and synchronized with the production schema.
- Do not run the generator on a CI/CD build server. If the build server database differs from the development database, the generated code will differ — causing hard-to-diagnose bugs. Generate once during development and commit the results to source control.
- Generated code is static — it does not change unless you explicitly re-run the generator.
- See Could this project be run by a script/build process? for more details on automation.