0

I have a .NET 6 Azure Function app project and clean architecture like setup. I have a EF Core 6 setup in persistence layer where database migrations reside. I understand we need design-time migrations as well.

Only one piece I am missing: how could I run database migrations automatically on function start up like in an ASP.NET Core 6 Web API project? Is there an efficient way to do this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sudipBanerjee
  • 37
  • 2
  • 9
  • This answer should be helpful: https://stackoverflow.com/a/64806909/1756249 – joostas Mar 23 '23 at 16:08
  • This doesn't answer how to run the migrations at function startup however? though I am thinking whether its a good practise to run db migrations on function startup in consumption plan as there is situation of cold start already. – sudipBanerjee Mar 24 '23 at 05:05

1 Answers1

0

How to run EF Core database migrations from an Azure Function startup.

Install the below NuGet packages.

Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design

  • We can use the same Migrate() as we do in the.NET 6 API startup.

whether its a good practice to run db migrations on function startup in consumption plan as there is situation of cold start already.

  • Even though it is possible to run DB migrations from functions startup (Consumption plan), it is not the recommended way to do.

  • It will increase the cold start time of the function which you are already facing.

  • To avoid this run the migrations outside the Startup.

  • This ensures that it is executed only when necessary, which helps in improving the performance of the Function.

To run EF Core database migrations automatically on function startup, we can use the IDesignTimeDbContextFactory interface to create a new instance of DbContext at design time.

This interface is used by EF Core tools to create a new instance of DbContext when running commands like dotnet ef migrations add or dotnet ef database update.

To use this interface, you need to create a new class that implements IDesignTimeDbContextFactory and returns a new instance of your DbContext.

Refer Entity Framework with Azure Functions for more details.

RohitVarun
  • 68
  • 3