Build a Complete App with ASP.Net, C#, SQL Lite – Part 4

This is part 4 of our complete application in ASP.Net, C# and SQL Lite. In this part, we would configure our application to run the migration at startup.

We’ll also create Seeders (scripts that inserts some initial data to the database) and make these seeders run at startup.

So let’s dive right in!

  1. About Web Host  and Web Host Extension
  2. Create the Web Host Extension
  3. Create the Seeders

 

About Web Host and Web Host Extension

First, what is the WebHost? This is the class responsible for handling application startup  and lifetime management. This includes logging, dependency injection and configuration.

You can take a look by opening the Startup.cs file

Now we would like to extend this class, so that when the application starts up, the migration and seeders are run as well.

 

Create the Web Host Extension

We would place this inside a folder called extensions. So follow the steps below:

Step 1 – Create a folder called Extensions

Step 2 – Inside this folder, create a class called WebHostExtensions. The content of this class is given below

public static class WebHostExtensions
{
    public static IHost Initialize( this IHost host)
    {
        using(var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var context = services.GetRequiredService<HospitalContext>();
            context.Database.Migrate();
        }
        return host;
    }
}

See the video for explanation.

Step 3 – Open your Program.cs file and adjust your main method like so

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    host.Initialize().Run();
}

 

Step 4 – Now you can run the program everything runs fine as well. Now delete the database and remove the connection. Run the program again, you will notice that the database is created again and all the tables are created as well.

Create the Seeders

So basically, we use seeders to add some initial data to the database. So for each of the table, we would have class. All of them would be in a folder. Let’s follow the steps;

Step 1 – Create a folder called Seeders.

Step 2 – Inside this folder, create a file called CountrySeeder (we start with this). The content of the CountrySeeder class is given below. So just copy and paste it.

public class CountrySeeder
{
    private readonly HospitalContext _context;
    public CountrySeeder(HospitalContext context)
    {
        _context = context;
    }

    public void Seed()
    {
        AddNewCountry(new Country { CountryId = 1, Name = "India", Capital = "New Delhi" });
        AddNewCountry(new Country { CountryId = 2, Name = "Nigeria", Capital = "Abuja" });
        AddNewCountry(new Country { CountryId = 3, Name = "Hungary", Capital = "Budapest" });
        _context.SaveChanges();
    }

    // since we run this seeder when the app starts
    // we avoid adding duplicates, so check first, then add
    private void AddNewCountry(Country country)
    {
        var existingType = _context.Countries.FirstOrDefault(c => c.CountryId == country.CountryId);
        if (existingType == null)
        {
            _context.Countries.Add(country);
        }
    }
}

Watch the video for an explanation of the codes.

Step 5 – Open the WebhostExtensions class and add the code below. Add it immediately under the context.Database.Migrate() line.

//Lets not seed the database by calling the seeders
new CountrySeeder(context).Seed();

 

Step 6 – Launch the application again. If everything works well, you can stop it. Now  if you open the database table you will see the three records we inserted as shown below:

Records Seeded to the Countries Table
Records Seeded to the Countries Table

 

Follow the same method to create the 7 remaining seeders. You can get the completed codes in the link in the video description

kindsonthegenius

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

Your email address will not be published.