You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide Migrations hooks to execute SQL and/or seeding before and after each migration has been applied #24710
I would like to include some custom sql (create stored procedure) in the generate migration script. This code should be run whenever the migration is executed, so no version constraint.
I tried to accomplish this with a custom MigrationOperation / SqlServerMigrationsSqlGenerator approach, but this does not work if there are no new migrations.
Is there another way to achieve this?
Thank you in advance for your Feedback.
Cheers
David
EF Core version: 5.0.5
Database provider: Microsoft.Data.SqlClient
Target framework: NET 5.0
Operating system: Windows
IDE: Visual Studio 2019 16.8
Reacted by lonix1, Pavel Voronin, Bernd Hirschmann, Rose Rey, Cody Batt, xxAtrain223, Andrei Ciudacov and François Paris
@riedd2 take a look at this section in our docs. tl;dr you can directly insert raw SQL to be executed as part of any migration - no need for either a custom MigrationOperation or touching SqlServerMigrationsSqlGenerator.
Hey @roji
Thanks for your answer.
I'm aware that I can execute raw sql in any migration but that does not solve my problem.
I would like to be able to run the custom sql even if there are no new migrations on every deployment (like seeding data but part of the migration script). My first approach was to try to add this every time the migration script gets created but that didn't seem to work. If I'm adding the raw sql in a migration it would only run once when the migration runs for the first time.
EF Core requires for there to be an unapplied migration in order to run any migration code - so if I'm understanding you correctly that isn't possible.
Can you provide a bit more context on what kind of SQL you would want to run on every deployment, regardless of whether new migrations have been created?
I have a list of stored procedures (create or alter statements) which are kept in a folder within my solution. These can change independent of other migration relevant code. I would like to apply them with every deployment to keep them up to date, hence my question if it would be possible to add them to the migration somehow.
I could make a migration every time one changes but that would make it harder to have a clean source control history, since I would need to check all the migration and not just the sql files itself.
Another avenue would be to run them on application start but since we are running multiple instances of the application (which can be restarted at any time) with the same database, this could introduce some problems with db locks and such.
It would also be possible to change our pipeline and have a separate step dedicated to run such code, this would be a clean solution but It's my second choice since it would mean a change to our pipeline.
Run them within the migration script would be the cleanest solution with the easiest integration in the existing pipeline.
If I understand you correctly, you're basically looking to drop/recreate (or re-define) your stored procedures every time you deploy your application to production, is that right?
If you're already using EF Core migrations and want to use them to manage your stored procedures as well, then we indeed recommend creating a new migration for any change; creating a new stored procedure would imply a new migration, as well as changing an existing one. I'm not sure why this would result in less clean source control history - it's seems to be purely a question of whether your raw SQL is in independent files, or embedded within migration files.
Otherwise, if you really just want to run arbitrary SQL DDL to manage your stored procedures (e.g. drop/create), then I don't really see what advantage there would be in doing so via EF Core... Just like you're applying new migrations to your production database on deployment, you could run your custom, raw SQL script from outside EF Core. One of the main points of migrations is that they're tracked in the database, so that EF Core can only apply pending ones; but you want to re-run the same raw SQL every time.
I just wanted to add how we accomplished this here before I close the issue.
Disclaimer: It's hacky, we track it as technical dept and we will fix it in the future. The usual things you tell yourself if you have tight project deadlines and time constraints.
The Implementation:
Create a custom migration, which reads the embedded resources sql and creates custom MigrationOperation based on it
A SqlServerMigrationsSqlGenerator implementation which takes care of adding the sql to the migration
Use a custom Migrator to add our custom migration to the migrations to apply
Replace the default SqlServerHistoryRepository implementation to not add a migration history check sql for our custom migration.
With this in place, changes and addition made to the sql files, will automatically be picked up and added to the end of every migration script that gets generated.
Thanks everyone for contributing to the discussion.
changed the title [-]Add default custom sql to migration script[/-][+]Provide Migrations hooks to execute SQL and/or seeding before and/or after migrations have been applied[/+]on Apr 29, 2021
The CustomMigrator helped me too! Thanks @RyanMarcotte :)
I'm still tinkering about to find a neat approach, so bear with me.
I used a separate folder with all the StoredProc scripts (& CustomMigration files):
(I did DBFirst with WideWorldImporters DB for general tinkering, so all the scripts are from there.)
And I only used a single EF Migration script. Pls ignore the Down():
For the Designer.cs, maybe it's not needed (not sure yet if it'll break anything; too knackered to keep going tonight):
Therefore I didn't need to intercept via a CustomHistoryRepository. Did use the CustomMigrator in exactly the same way, though.
One thing I also did was to add this to each StoredProc script:
Probably not the best approach, but it's the best I can think of for now to ensure the StoredProc is always the most updated version, whenever there are changes made to the StoredProc scripts.
@RyanMarcotte thank you! That's the least terrible solution I've seen around.
For others, the problem as I see it, with not having a post migration hook is:
Stored Procedures, Views, TVFs, Functions, etc all rely on an underlying table structure that might have changed underneath us. The DB Server will validate that when its created, but not if a dependent table changes, meaning we only find out at runtime instead of compile time. Fine if you have 100% test coverage, but I've yet to see a commercial project that does.
Having to replicate the whole stored proc in a migration each time makes it very difficult for reviewers / code archaeologists to see what's changed - it's counter to working in a team. It's also difficult to work out which version is supposed to be the correct one (at as given point in time) when debugging.
From my vantage point (though I'm new to .NET core - in the process of migrating from .NET Framework) it looks like the "recommended" solution to create seed data (which is where I added this sort of modification in EF6) on app initialization means granting extra permissions to a web app that I don't want it to have. If I accidentally let through a sql injection, I don't want the web app's DB user to have permission to drop or create tables. There is also the locking/contention issues mentioned above. I also don't want my app start-up performance hindered by something that doesn't need to happen in-process.
The DB Server will validate that when its created, but not if a dependent table changes, meaning we only find out at runtime instead of compile time.
Assuming you're in SQL Server, you may be interested in "schema binding" (link) - this forbids changing a table's schema if e.g. it affects a view that's defined on top of it. Other databases typically have similar mechanisms.
As suggested by @bricelamhere, this could also cover calling ReloadTypes() in Npgsql, to reload any PostgreSQL types that may have been added as part of the migrations (e.g. an extension was added). This would require giving access to the DbConnection.
@roji is there a reason why people shouldn't run idempotent SQL on every deployment? Seems like there are a few people that want this bad enough to work around it. Is this a bad idea for some reason other than "EF doesn't work this way"? These workarounds are both cool and ridiculous.
@roji Thanks for point me to interceptors. I thought I know well EF Core docs, but it looks like I missed that. If I may suggest something, from my perspective it will be nice to have dedicated page in doc for EF Migration customization rather than under logging and events parent page. It is just my feeling
In terms of idempotency and migration scripts. As far as I understood idempotent migration scripts operations work by checking if migration has been already run and if that is true not running such migration again. If we talk about such idempotency, it is very limited one. Typical create and replace command are idempotent, if you run them, they will truly change state of DB, while in EF nothing will happen once migration has been applied. If I can be honest my interpretation of idempotent migration scripts (maybe bad one) was that they are more to handle gracefully use cases where it is hard to know in advance if migration has been run or not. The other thing is, that even if I will not add --idempotent argument to script call, I cannot re-run same migration to apply diff change update on it. To sum up my understanding: idempotent migration scripts are far different concept to what is supported in liquibase or flyway as the repeatable migration and what I think other were comment in this issue.
changed the title [-]Provide Migrations hooks to execute SQL and/or seeding before and/or after migrations have been applied[/-][+]Provide Migrations hooks to execute SQL and/or seeding before and after each migration has been applied[/+]on Jul 12, 2024
Activity
roji commentedon Apr 21, 2021
@riedd2 take a look at this section in our docs. tl;dr you can directly insert raw SQL to be executed as part of any migration - no need for either a custom MigrationOperation or touching SqlServerMigrationsSqlGenerator.
riedd2 commentedon Apr 21, 2021
Hey @roji
Thanks for your answer.
I'm aware that I can execute raw sql in any migration but that does not solve my problem.
I would like to be able to run the custom sql even if there are no new migrations on every deployment (like seeding data but part of the migration script). My first approach was to try to add this every time the migration script gets created but that didn't seem to work. If I'm adding the raw sql in a migration it would only run once when the migration runs for the first time.
Sorry if my question was not clear.
roji commentedon Apr 21, 2021
EF Core requires for there to be an unapplied migration in order to run any migration code - so if I'm understanding you correctly that isn't possible.
Can you provide a bit more context on what kind of SQL you would want to run on every deployment, regardless of whether new migrations have been created?
riedd2 commentedon Apr 21, 2021
That's what I feared.
I have a list of stored procedures (create or alter statements) which are kept in a folder within my solution. These can change independent of other migration relevant code. I would like to apply them with every deployment to keep them up to date, hence my question if it would be possible to add them to the migration somehow.
I could make a migration every time one changes but that would make it harder to have a clean source control history, since I would need to check all the migration and not just the sql files itself.
Another avenue would be to run them on application start but since we are running multiple instances of the application (which can be restarted at any time) with the same database, this could introduce some problems with db locks and such.
It would also be possible to change our pipeline and have a separate step dedicated to run such code, this would be a clean solution but It's my second choice since it would mean a change to our pipeline.
Run them within the migration script would be the cleanest solution with the easiest integration in the existing pipeline.
roji commentedon Apr 21, 2021
If I understand you correctly, you're basically looking to drop/recreate (or re-define) your stored procedures every time you deploy your application to production, is that right?
If you're already using EF Core migrations and want to use them to manage your stored procedures as well, then we indeed recommend creating a new migration for any change; creating a new stored procedure would imply a new migration, as well as changing an existing one. I'm not sure why this would result in less clean source control history - it's seems to be purely a question of whether your raw SQL is in independent files, or embedded within migration files.
Otherwise, if you really just want to run arbitrary SQL DDL to manage your stored procedures (e.g. drop/create), then I don't really see what advantage there would be in doing so via EF Core... Just like you're applying new migrations to your production database on deployment, you could run your custom, raw SQL script from outside EF Core. One of the main points of migrations is that they're tracked in the database, so that EF Core can only apply pending ones; but you want to re-run the same raw SQL every time.
ajcvickers commentedon Apr 23, 2021
@bricelam I couldn't find the old-style seeding issue you mentioned in triage.
bricelam commentedon Apr 26, 2021
I can't find it either...
riedd2 commentedon Apr 26, 2021
I just wanted to add how we accomplished this here before I close the issue.
Disclaimer: It's hacky, we track it as technical dept and we will fix it in the future. The usual things you tell yourself if you have tight project deadlines and time constraints.
The Implementation:
MigrationOperationbased on itSqlServerMigrationsSqlGeneratorimplementation which takes care of adding the sql to the migrationMigratorto add our custom migration to the migrations to applySqlServerHistoryRepositoryimplementation to not add a migration history check sql for our custom migration.With this in place, changes and addition made to the sql files, will automatically be picked up and added to the end of every migration script that gets generated.
Thanks everyone for contributing to the discussion.
[-]Add default custom sql to migration script[/-][+]Provide Migrations hooks to execute SQL and/or seeding before and/or after migrations have been applied[/+]12 remaining items
margohpolo commentedon Nov 22, 2022
The CustomMigrator helped me too! Thanks @RyanMarcotte :)
I'm still tinkering about to find a neat approach, so bear with me.
(I did DBFirst with WideWorldImporters DB for general tinkering, so all the scripts are from there.)
Therefore I didn't need to intercept via a CustomHistoryRepository. Did use the CustomMigrator in exactly the same way, though.
One thing I also did was to add this to each StoredProc script:
Probably not the best approach, but it's the best I can think of for now to ensure the StoredProc is always the most updated version, whenever there are changes made to the StoredProc scripts.
Overall though, would this be a neater approach?
michaelmalonenz commentedon Oct 27, 2023
@RyanMarcotte thank you! That's the least terrible solution I've seen around.
For others, the problem as I see it, with not having a post migration hook is:
roji commentedon Oct 27, 2023
Assuming you're in SQL Server, you may be interested in "schema binding" (link) - this forbids changing a table's schema if e.g. it affects a view that's defined on top of it. Other databases typically have similar mechanisms.
roji commentedon Nov 16, 2023
As suggested by @bricelam here, this could also cover calling ReloadTypes() in Npgsql, to reload any PostgreSQL types that may have been added as part of the migrations (e.g. an extension was added). This would require giving access to the DbConnection.
CodyBatt commentedon Feb 6, 2024
@roji is there a reason why people shouldn't run idempotent SQL on every deployment? Seems like there are a few people that want this bad enough to work around it. Is this a bad idea for some reason other than "EF doesn't work this way"? These workarounds are both cool and ridiculous.
jacekmlynek commentedon Jun 26, 2024
roji commentedon Jun 27, 2024
jacekmlynek commentedon Jun 27, 2024
@roji Thanks for point me to interceptors. I thought I know well EF Core docs, but it looks like I missed that. If I may suggest something, from my perspective it will be nice to have dedicated page in doc for EF Migration customization rather than under logging and events parent page. It is just my feeling
In terms of idempotency and migration scripts. As far as I understood idempotent migration scripts operations work by checking if migration has been already run and if that is true not running such migration again. If we talk about such idempotency, it is very limited one. Typical create and replace command are idempotent, if you run them, they will truly change state of DB, while in EF nothing will happen once migration has been applied. If I can be honest my interpretation of idempotent migration scripts (maybe bad one) was that they are more to handle gracefully use cases where it is hard to know in advance if migration has been run or not. The other thing is, that even if I will not add
--idempotentargument to script call, I cannot re-run same migration to apply diff change update on it. To sum up my understanding: idempotent migration scripts are far different concept to what is supported in liquibase or flyway as the repeatable migration and what I think other were comment in this issue.[-]Provide Migrations hooks to execute SQL and/or seeding before and/or after migrations have been applied[/-][+]Provide Migrations hooks to execute SQL and/or seeding before and after each migration has been applied[/+]DanieleVar commentedon Dec 4, 2025
Thanks @riedd2 and @RyanMarcotte for yours snippets! :)