-
Create and add a new project named
BackEnd
and name the solutionConferencePlanner
using File / New / ASP.NET Core Web API. Select the Web API template, No Auth, no Docker support. Uncheck the box that says "Use controllers (uncheck to use minimal APIs)".
If not using Visual Studio, create the project using the dotnet cli at the command line as follows:
-
Create folder ConferencePlanner and create a solution by running the following console command:
dotnet new sln
-
Create sub-folder BackEnd and create a project by running
dotnet new webapi -minimal
-
Add the project to the solution using the following command
dotnet sln add BackEnd/BackEnd.csproj
-
Open the solution in Visual Studio Code by running the following command:
code .
-
Add a new
Models
folder to the root of the application. -
Add a new
Speaker
class using the following code:using System.ComponentModel.DataAnnotations; namespace BackEnd.Models; public class Speaker { public int Id { get; set; } [Required] [StringLength(200)] public string? Name { get; set; } [StringLength(4000)] public string? Bio { get; set; } [StringLength(1000)] public virtual string? WebSite { get; set; } }
Before you start, you need to add the required packages.
-
In Visual Studio, right click the project and select
Manage NuGet Packages...
, then selectBrowse...
and search forMicrosoft.EntityFrameworkCore.Sqlite
and clickInstall
. -
Search for
Microsoft.EntityFrameworkCore.Tools
and clickInstall
.
-
From the terminal, run the following command:
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
This command adds the NuGet package that contains the EF Core SQLite database provider and all its dependencies, including the common EF Core services.
-
Next we'll create a new Entity Framework DbContext. Create a new
ApplicationDbContext
class in theModels
folder using the following code:using Microsoft.EntityFrameworkCore; namespace BackEnd.Models { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Speaker> Speakers => Set<Speaker>(); } }
Note We're using the
=>Set<Speaker>)()
on that last line to deal with nullable warnings, since we know that EF Core will be initializing thisDbSet
. -
Add a connection string to the appsettings.json file for this database:
{ "ConnectionStrings": { "DefaultConnection": "Data Source=ConferencePlanner.db" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
-
Just below the top line of
Program.cs
, add the code read the connection string from the appsettings.json file and set up the Sqlite database, so that it reads as follows:var builder = WebApplication.CreateBuilder(args); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? "Data Source=conferences.db"; builder.Services.AddSqlite<BackEnd.Models.ApplicationDbContext>(connectionString);
This code registers the
ApplicationDbContext
service so it can be injected into controllers. Additionally, it configures Entity Framework to use SQLite with the configured connection string.
You will be using either a terminal window or the Visual Studio Developer PowerShell terminal for the following steps.
-
If you are using Visual Studio, open the Developer PowerShell terminal by selecting View -> Terminal and enter
cd BackEnd
. -
If you are using a terminal window, navigate to the project directory (the directory containing the
Program.cs
file). -
Install the required NuGet package for migrations:
dotnet add package Microsoft.EntityFrameworkCore.Design
-
Install the EntityFramework global tool
dotnet-ef
using the following command:dotnet tool install -g dotnet-ef
-
If you receive a message that the tool is already installed, update to the newest version with the following command:
dotnet tool update -g dotnet-ef
-
Build the project using the following command:
dotnet build
-
Run the following commands in the command prompt:
dotnet ef migrations add Initial dotnet ef database update
Commands Explained
Command | Description |
---|---|
dotnet ef migrations add Initial |
Generates code to create the initial database schema based on the model specified in 'ApplicationDbContext.cs'. Initial is the name of the migration. |
dotnet ef database update |
Creates the database and runs all newly created migrations (in this case, just the Initial migration). |
For more information on these commands and scaffolding in general, see this tutorial.
If your database ever gets in a bad state and you'd like to reset things, you can use
dotnet ef database drop
followed bydotnet ef database update
to remove your database and run all migrations again.
Scroll down to the bottom of Program.cs
and you'll see some sample code for the Weather Forecast API:
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
You'll see a simple API that returns weather forecasts and is mapped to the HTTP GET verb. You'll see the output of this API in a bit, but first we'll build our own API for the Speakers
model class.
- Create a new Endpoints directory in the BackEnd project.
- Right-click the Project and select Add > New Scaffolded Item.... Select API with read/write endpoints, using Entity Framework and click Add.
- In the dialog, select the
Speaker
model for the Model Class. - Click the + button to add a new endpoint named
SpeakerEndpoints
. - Select
ApplicationDbContext
for the "Data Context Class" and click the Add button. - Check the Enable Open API checkbox and click the Add button.
-
Install the
aspnet-codegenerator
global tool by running the following command:dotnet tool install -g dotnet-aspnet-codegenerator
-
If you receive a message that the tool is already installed, update to the newest version with the following command:
dotnet tool update -g dotnet-aspnet-codegenerator
Note** You may need to close and reopen the console window to be able to use this tool.
-
Run the following command to view the help for the
minimalapi
scaffolding command:dotnet aspnet-codegenerator minimalapi --help
-
Run the following in the project folder at the cmd line:
dotnet aspnet-codegenerator minimalapi -e SpeakerEndpoints -dc ApplicationDbContext -o -m BackEnd.Models.Speaker
This scaffolder does two things:
-
It generates an endpoints class named
SpeakersEndpoints
with API endpoints that map to database operations using theApplicationDbContext
class and theSpeaker
model. -
It adds the follwing code to the
Program.cs
file to register the endpoints class:
app.MapSpeakerEndpoints();
We'll make a quick improvement to add tags to the SpeakerEndpoints class so it works a little better with Open API.
-
Open the
SpeakersEndpoints.cs
file in the project folder. -
Open the Quick Replace menu using Edit / Find and Replace / Quick Replace.
-
In the Find textbox, enter
.WithName(
-
In the Replace textbox, enter
.WithTags("Speaker").WithName(
-
Select Replace All (Alt-A)
In this section, we'll be interacting with the API using the Swagger UI web interface. Swagger is a machine readable representation of a RESTful API that enables support for interactive documentation, client SDK generation and discoverability.
-
Run the application (F5 in Visual Studio or
dotnet run
from console). -
If the browser does not automatically open, browse to the Swagger UI at
http://localhost:<random_port>/swagger
. -
First, click on the GET button in WeatherForecast section. You'll see the values that were listed in the
WeatherForecastController
earlier. -
In the Speakers section, click on the GET button. You'll see there are no speakers returned. Let's add one!
-
In the Speakers section, click on the POST button. Referencing the example on the right, fill in a speaker request. Leave the
ID
blank, that will be filled in by the database.{ "name": "Dr. Steven Strange", "bio": "Formerly a renowned surgeon, Doctor Stephen Strange now serves as the Sorcerer Supreme.", "webSite": "https://giphy.com/search/doctor-strange" }
-
When you click the Execute button, you should see a success response from the server. Now, trying out the GET endpoint above should show your newly added speaker.
Next: Session #2 - Back-end