How to run Migration automatically in the program.cs in .Net Core 6.
How to run Migration automatically in program.cs in .Net Core 6.
737
07-Nov-2023
Updated on 08-Nov-2023
Aryan Kumar
08-Nov-2023In .NET Core 6, you can run database migrations automatically when your application starts by adding code in the Program.cs file. This can be useful to ensure that the database is up-to-date before the application starts. Here's how you can achieve this:
Install Entity Framework Core and Migrations: Make sure you have Entity Framework Core and the necessary packages for your database provider installed in your project. If not, you can add the packages using the following commands:
For SQL Server, for example:
For SQLite:
Be sure to install the package that corresponds to your database provider.
Add Database Context: Create a database context class that inherits from DbContext. This class represents the database and includes the DbSet properties for your models. For example:
Configure and Run Migrations in Program.cs: In your Program.cs file, configure the database context and apply migrations as follows:
In the code above:
Replace YourEntity and Connection String: Replace YourEntity with the actual entity class used in your application and configure the database connection string in the CreateHostBuilder method.
Now, when you run your .NET Core 6 application, it will automatically apply pending database migrations before starting the application. This ensures that your database is up-to-date with the latest schema changes.