Computer Magic Logo
Update database

Saturday, December 10, 2016

Published by Aristotelis Pitaridis

When we create new migrations for our modes, we will have to update the database in order to apply the changes. First of all we have to open the package manager console by opening the Tools menu and we select the 'Package Manager Console' from the 'NuGet Package Manager' submenu. After that we type the following command in the package manager console.

Update-Database

If we want the database to automatically update the database using the migrations that we created we can add the following code at the top of the Configure method of the Startup.cs file.

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
using (var context = new ApplicationDbContext(optionsBuilder.Options))
{
    context.Database.Migrate();
}

The DefaultConnection is used to define the connection string in an ASP.NET core web site for the default template. This value may be different depending on the project that we work.