Lesson Weekend

Let's start work on our Cretaceous Park API. While the CLI scaffolded the basics for us, we'll still need to set up and configure our own database, controller, and models.

Database Setup Review


We'll add the necessary packages to our project:

$ dotnet add package Microsoft.EntityFrameworkCore -v 5.0.0
$ dotnet add package Pomelo.EntityFrameworkCore.MySql -v 5.0.0-alpha.2  

Adding a Model


Now, let's create our models.

We'll create an Animal class first (you'll need to create the Models folder as well):

Models/Animal.cs
namespace CretaceousPark.Models
{
    public class Animal
    {
        public int AnimalId { get; set; }
        public string Name { get; set; }
        public string Species { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
    }
}

Next, let's create a DbContext class in a file called CretaceousParkContext.cs:

Models/CretaceousParkContext.cs
using Microsoft.EntityFrameworkCore;

namespace CretaceousPark.Models
{
    public class CretaceousParkContext : DbContext
    {
        public CretaceousParkContext(DbContextOptions<CretaceousParkContext> options)
            : base(options)
        {
        }

        public DbSet<Animal> Animals { get; set; }
    }
}

Next, we'll have to add a couple of using statements and edit our ConfigureServices method in Startup.cs so that we can use MySql, and remove the previous Swagger configuration. We'll also get rid of some unnecessary using statements in the process. Our new Startup.cs file should look like this:

CretaceousPark/Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using CretaceousPark.Models;

namespace CretaceousPark
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<CretaceousParkContext>(opt =>
                opt.UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"])));
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Our ConfigureServices method contains a call to the UseMySql method which depends on the connection string defined in our appsettings.json file. Since the CLI does not automatically define a connection string, we'll have to add one. Let's update appsettings.json now:

CretaceousPark/appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Port=3306;database=cretaceous_park;uid=root;pwd=[YOUR-PASSWORD-HERE];"
  }
}

Now we're ready to run our migration.

$ dotnet add package Microsoft.EntityFrameworkCore.Design -v 5.0.0
$ dotnet ef migrations add Initial
$ dotnet ef database update

In the next lesson, we'll start writing custom API endpoints.

Repository Reference

Follow the link below to view how a sample version of the project should look at this point. Note that this is a link to a specific commit in the repository.

Example GitHub Repo for Cretaceous Park

Lesson 4 of 22
Last updated April 6, 2022