Adding automatic migrations

EF Core migration files encapsulate all the steps needed to reach a database structure that conforms to your code models, but in order to apply those steps to your database, there are a few different paths that you can take:

  • Generate an SQL script and execute it in your database
  • Run the external dotnet migrate command from the terminal
  • Add automatic migration capability to your application code.

 All of the mentioned methods are good, but I will concentrate on the third option because it's the most developer-friendly and allows you to move fast as you add new features. 

The DatabaseFacade object, held by the DbContext and exposed by the Database property, contains the Migrate method that runs the migration process for you. To use this method, we need to get hold of the DbContext object and run the migration on the earliest phase of our application. The best location to do so is in your Program class, right before the WebHost is run.

Change your Program.Main method to the following code snippet:

public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetService<GiveNTakeContext>();
try
{
context.Database.Migrate();
}
catch (Exception ex)
{
// Error handling
}
}
host.Run();
}

The preceding code creates the WebHost (described in Chapter 3, Creating a Web Application with ASP.NET Core) and afterwards uses the ASP.NET Core Dependency Injection capabilities to create a scoped region to resolve the GiveNTakeContext object and call its Migrate method. The CreateScope method creates a disposable IServiceScope that control the lifetime of the resolved objects. Once disposed, all the scoped objects will be disposed as well. 

Now, build and run your application. The GiveNTake database will be automatically created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.4.167