Skip to content

Improve experience deploying databases created by Migrations #19587

Open

Description

@ajcvickers

This is a grouping of related issues. Feel free to vote (👍) for this issue to indicate that this is an area that you think we should spend time on, but consider also voting for individual issues for things you consider especially important.


Currently, many developers migrate their databases at application startup time. This is easy but is not recommended because:

  • Multiple threads/processes/servers may attempt to migrate the database concurrently
  • Applications may try to access inconsistent state while this is happening
  • Usually the database permissions to modify the schema should not be granted for application execution
  • Its hard to revert back to a clean state if something goes wrong

We want to deliver a better experience here that allows an easy way to migrate the database at deployment time. This should:

  • Work on Linux, Mac, and Windows
  • Be a good experience on the command line
  • Support scenarios with containers
  • Work with commonly used real-world deployment tools/flows
  • Integrate into at least Visual Studio

The result is likely to be many small improvements in EF Core (for example, better Migrations on SQLite), together with guidance and longer-term collaborations with other teams to improve end-to-end experiences that go beyond just EF.


Done in 6.0

Done in 9.0

Backlog

Activity

  1. added this to the 5.0.0 milestone on Jan 14, 2020
  2. removed this from the 5.0.0 milestone on Jan 14, 2020
  3. ErikEJ commented on Jan 14, 2020

    @ErikEJ
    Contributor

    sqlpackage / dacpac already does much of this - but sadly currently only for SQL Server.

  4. BEagle1984 commented on Jan 14, 2020

    @BEagle1984

    In our latest project we integrated the DB migrations in the deployment pipeline simply by generating an idempotent migration script (for all migration steps) via dotnet-ef and leveraging sqlcmd to execute it against the appropriate sql server instance. We do this in Jenkins, from a Linux slave.
    I honestly don’t think our solution is too bad.

  5. added this to the 5.0.0 milestone on Jan 17, 2020
  6. macsux commented on Feb 7, 2020

    @macsux

    So I've built something that helps with this that was contributed to project SteelToe. It allows tasks to be bundled with app and launched via special command argument. Ef migration is one of them.
    Is you're not familiar with SteelToe, the site is https://steeltoe.io

    These are the relevant sources you may consider

    https://github.com/SteeltoeOSS/Management/tree/dev/src/Steeltoe.Management.CloudFoundryTasks

    https://github.com/SteeltoeOSS/Connectors/blob/dev/src/Steeltoe.CloudFoundry.Connector.EFCore/MigrateDbContextTask.cs

  7. johnnyreilly commented on Feb 8, 2020

    @johnnyreilly

    Thanks for linking to this @AndriySvyryd - great to see this is being actively worked on

  8. dazinator commented on Feb 9, 2020

    @dazinator

    I ended up architecting my app to address these points, and putting all the logic in a reusable library which I might open source in future.

    • A lock file in shared storage directory (directory seen by all instances) to ensure only one instance can run the migrations at a time.
    • An mvc Action filter which rejects requests by default when there are EF pending upgrades detected and includes a header in the response so that the client can detect that the server requires ef core migrations to be applied and can display a suitable UI.
    • A blazor component and http client delegate handler to be used in blazor wasm applications that can auto detect the header in responses from the server and display an Upgrade pending screen, with an option for a deployment admin to login and apply.
    • An MVC controller with an Action method that can be called to Apply the pending EF core migrations. This is excluded from the action filter mentioned above that rejects requests and is instead only available when there are pending migrations to apply. I've applied authorization to this method so it requires "deployment admin" role.
    • A custom authentication scheme that allows a "deployment admin" to login using a login method that places no dependency on the application database for obvious reasons. This custom auth scheme generates a code and writes it to a file in the storage directory (same location as where the lock file also gets written). A person with access to that directory can then grab the code and use it to log in with which creates a claims principal with Deployment Admin role, and then allows them to see the pending migrations and click a button to apply them (I.e this calls the mvc action method mentioned above)

    There was quite a bit to it in the end.
    I havent addressed rollback.. but being able to rollback is not necessarily safe if data is going to be lost in the process, so the safest policy for me tends to be to only allow roll forward, and make sure migrations are tested adequately before rolling to a production environment.

    One thing I like about this approach is that I can deploy a new version of my application using azure app service for containers, and when the new instance is swapped in and it has pending migrations, anyone currently using the app will now get presented with a UI that says an upgrade is in progress. Once its applied they can use the app again. Contrast this to upgrading the database during the deployment: if the database is upgraded prior to the new version of the app being swapped in, then current users will be using an older version of the app whilst its database is being upgraded to a newer version from under it - which could introduce errors. If the database is upgraded by the deployment process after the newer version of the app is swapped in, then unless the application is taken fully down until the db upgrade is complete then users will be potentially using a new version of the app before the db upgrade is complete which again can cause errors. With my approach, the app is not taken fully offline which allows me to provide a nicer experience for end users whilst the upgrade is taking place. Likewise if there are mvc methods that I know have no dependency on the database I can optionally keep them functional during the upgrade by excluding them from the action filter.

    Basically unless EF migrations can be committed in a transaction and the corresponding version of the app swapped in to replace the old version in a single atomic operation, then you've got the potential for version mismatch for some period of time. I dont think the above is possible with app service for containers but if anyone knows different please do share!

  9. ajcvickers commented on Feb 10, 2020

    @ajcvickers
    ContributorAuthor

    @dazinator Thanks for sharing that. There is certainly some interesting things there--we talked about going in this kind of direction before, but robustness has always been a concern. If you do create a package I would be interested in taking a look.

  10. syndicatedshannon commented on Feb 10, 2020

    @syndicatedshannon

    This product is pretty strong with this latest 3.0 release. It's great to see, since we decided not to bail on it during the rewrite.

    I'm disheartened, though, that this capability is slated for 5.0, but still very little attention is being given to contract-first, conceptual model-first, database-first, or SSDT/.SQLPROJ-authoritative development. Is it just that there are insufficient requests for it, or is EF not intended for that market?

    The semantics of up/down are great for early development, and I appreciate that they pull a lot of teams into EF during envisioning stages. Also, the syntax of EF's C# attribute-modelled and fluent definition are well-designed. Even so, this leaves a lot of gaps in both relational and constraint capability and support for collaboration with data designers. SQL code embedded as text strings in fluent definitions (without even schema validation), to me, means something is wrong. Which team writes that code? The team I have to allocate with both expert level C# lambda AND T-SQL background?

    I know this all reveals my personal stance on code-first data development. The point is, I wonder where this feature is heading. Who needs to do this; who needs DACPAC-like deployment but wouldn't be better suited to getting SQL schema definitions out of C# and into source-controlled SQL, or a contract-first toolset?

    Thanks for listening.

  11. ErikEJ commented on Feb 11, 2020

    @ErikEJ
    Contributor

    @syndicatedshannon I assume you are aware that EF Core Power Tools supports exactly that workflow (database first from a .dacpac/ .sqlproj)

  12. syndicatedshannon commented on Feb 13, 2020

    @syndicatedshannon

    @ErikEJ - Thank you. Our team has visited that tool often in the past, starting when you first suggested it years ago. We had various challenges along the way. At last visit, I believe we did not see how to make it work for us to get schema revisions applied to our models as part of our toolchain. My recollection is there is an effortful process to replace the model each time, even if we weren't concerned about losing model customizations. Since then we purchased LLBLGen, but I would love to know if I'm missing something.

  13. 68 remaining items

  14. roji commented on Apr 26, 2022

    @roji
    Member

    @GeorgeTTD how would the proposed --split-destructive switch work if there are more than one migrations pending, each with its own non-destructive and destructive components?

    More generally, you are of course free to structure your migrations in this way, and that's indeed what zero-downtime migrations usually entail; but this isn't really something EF Core can automate for you without your own planning and inspection of migrations.

  15. dazinator commented on Apr 26, 2022

    @dazinator

    @GeorgeTTD @roji If EF did mark destructive migrations with an attribute e.g

    [Destructive()]
    public partial class SomeMigration
    {
    
    }
    

    Then @GeorgeTTD you could atleast get part way there with the following:-

    1. Use two seperate migrations assemblies, for destructive vs non destructive.
    2. Add a test to assert this convention - uses reflection to discover migrations with or without this attribute and makes sure they haven't accidentally been added to the wrong project.
    3. You can now run each migrations assembly independently as required..

    However I'm not sure this makes sense as could you get scenarios where a non destructive migration depends on a destructive one if that was the order they were generated. For example a migration to do a column rename (destructive) could be generated before a migration to add an index on that column (non destructive).. For this reason it might be the best you can do is just to know whether the release does or doesn't contain non destructive migrations and optimise your deployment accordingly - they still need to be applied in the same collective order they were generated in.

  16. dazinator commented on Apr 26, 2022

    @dazinator

    Just to be clear, my proposition with the [Destructive] stuff was for EF to support a workflow that prevents teams from accidentally including Destructive migrations in a release. The value is that by deterring this it allows deployment flows where services need not be brought down whilst the database is being upgraded. It allows support of workflows where releases containing destructive migrations can be done, but behind a safety net that lends itself to better team communication and planning around it, as it can no longer be done "accidentally".

  17. roji commented on Apr 27, 2022

    @roji
    Member

    @dazinator as you write above, migrations are a linear, ordered list, with dependencies between them. It isn't possible to execute only non-destructive migrations, deferring destructive ones that are interspersed between them (because of the dependencies). So splitting migrations into separate assemblies (or otherwise cherry-pick/separating them) doesn't seem possible.

    However, in your second comment you seem to be proposing a cmdline switch where the EF Core tooling would simply refuse to apply migrations (e.g. when running a migrations bundle or dotnet ef database update) if any of them contain (or come after) a destructive migration. That does seem possible, and could possibly help prevent accidental errors, though note that any migrating would be blocked once a destructive migration is pending; I'm not sure exactly how that helps the workflow.

    At the end of the day, zero-downtime migrations are something which require careful planning and a specific workflow; EF can certainly try to help, but nothing will obviate a manual checking and migration planning here.

    Regardless, if you want to continue discussing this, please open a new issue - let's try to keep this general issue clear of detailed specific discussions.

  18. added
    composite-issue
    on Dec 6, 2022
  19. modified the milestones: , Backlog on Dec 6, 2022
  20. stijnherreman commented on Jan 31, 2023

    @stijnherreman

    In our latest project we integrated the DB migrations in the deployment pipeline simply by generating an idempotent migration script (for all migration steps) via dotnet-ef and leveraging sqlcmd to execute it against the appropriate sql server instance.

    I ended up with the same solution. The idempotent script is an artifact published by the build stage and is executed with sqlcmd.

    - task: PowerShell@2
      inputs:
        targetType: inline
        script: |
          Import-Module SqlServer
          Invoke-Sqlcmd -ServerInstance <...> -Database <...> -InputFile <...>

    One thing I'd still like to add is the ability to review the generated script in a pull request. GitHub has done this and open sourced their code, so I'm hoping to use their work as inspiration.

  21. removed their assignment
    on Jul 8, 2023
  22. alrz commented on Nov 2, 2023

    @alrz
    Member

    Is there any issue regarding something like "fluent migrations", that is, instead of inferring the changes from the model, you explicitly call into AddColumn(e => e.NewColumn), run sql, etc, to make a versioned migration script. I think that would address most of the pain points I've faced in the past,

  23. ajcvickers commented on Nov 2, 2023

    @ajcvickers
    ContributorAuthor

    @alrz If you want to write a migration where you explicitly call the builder methods instead of scaffolding the starting point from the model, then you are free to do that. You can then create a script from this in the normal way.

  24. added theissue type on Jun 15, 2025
  25. changed the issue type fromtoon Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-migrationsarea-toolscomposite-issue

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions