Creating a Database
In this lesson, we'll creating our database based on the migration
Creating our database#
In the last lesson, we created our first migration using the code first approach; dotnet ef tool helped us to create the migration. Now let's see what we can do with the database. Let's clear the terminal, type
dotnet ef database -h and press enter. As you can see, we have an option to update and to drop which makes it very clear which one we want to use now. The update command will create the database upon the migration we created in the last lesson. It is built upon the latest migration and makes the changes to the database accordingly. This is our first time; we don't have to look for the changes, it will create the database from scratch.
Check the database options available:
Well, this is one way of creating it and it certainly works. Try it if you want to, but we want our database to be filled with some data when it first starts. So what we want is to check if there is any database; if there's none, we want to create a database and fill it with some initial data. To do this, we'll have to go to a class which is invoked first when the server starts. It's a Main method and it's inside the
To set it up, we need to make some changes to our main method. First of all, we'll have to put this method inside a variable. Let's name it host and remove run because we want to set up the migration before we finally run this method, so our host variable is storing this command. Let's create another variable and call it scope. This variable will contain
host.Services.CreateScope(). We will see an error, which means we have to run the quick fix and call Dependency Injection to this class. What we want is to dispose this variable after we are finished using it; we don't want it to be hanging here forever, so we'll use the
using keyword before this variable, and what it'll do is that it will dispose this variable after the method is correctly executed. It is one of those things we want to dispose of after we're done using them.