Friday, November 20, 2026

Build a simple AI-powered weather assistant using the GitHub Copilot SDK and .NET

In this tutorial, we will build an AI-powered weather assistant using the GitHub Copilot SDK and .NET. To keep the focus on the core concepts, we'll develop the application as a simple console app.

Our assistant will answer a straightforward question:

What is the weather in Vancouver?

Along the way, you will learn how to:
  1. Create a .NET project
  2. Install and configure the GitHub Copilot SDK
  3. Build a custom tool
  4. Register the tool with the agent
  5. Create an AI agent
  6. Process user prompts and generate responses

By the end of this tutorial, you will have a working AI agent that can use tools to retrieve weather information and respond intelligently to user requests.

Agent workflow

The GitHub Copilot SDK supports .NET as one of its supported languages.

Step 1: Create a .NET console project

dotnet new console -n WeatherAgent
cd WeatherAgent
mkdir Helpers

Add the GitHub Copilot SDK packages:

dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Agents.AI.GitHub.Copilot

Step 2: Create the weather tool

Open the WeatherAgent folder in Visual Studio Code. In the project root folder, create a simple weather tools service file named WeatherTools.cs with this C# code:

using System.Globalization;
using System.Text.Json;

namespace WeatherAgent;

// Provides weather lookup functionality for AI tools.
public static class WeatherTools {

    // Gets and formats the current weather for a city.
    public static async Task<string> GetWeatherAsync(string city) {
        return (await GetWeatherByCity(city)).ToString();
    }

    // Resolves the city's coordinates before requesting its current conditions.
    static async Task<Weather> GetWeatherByCity(string city) {
        using HttpClient client = new();

        // The forecast API needs coordinates, so first resolve the city name.
        // Escape the name to safely include spaces and special characters in the URL.
        string encodedCity = Uri.EscapeDataString(city);
        string geoUrl = $"https://geocoding-api.open-meteo.com/v1/search?name={encodedCity}&count=1";
        string geoJson = await client.GetStringAsync(geoUrl);
        using JsonDocument geoDoc = JsonDocument.Parse(geoJson);

        // Stop here if geocoding did not find a city instead of requesting 
// a forecast with invalid coordinates.
if (!geoDoc.RootElement.TryGetProperty("results", out JsonElement results) || results.GetArrayLength() == 0) { throw new InvalidOperationException($"City '{city}' not found."); } // Read the first geocoding match and its timezone for the local-time display. JsonElement firstResult = results[0]; double latitude = firstResult.GetProperty("latitude").GetDouble(); double longitude = firstResult.GetProperty("longitude").GetDouble(); string name = firstResult.GetProperty("name").GetString() ?? city; string country = firstResult.GetProperty("country").GetString() ?? ""; string timeZoneId = firstResult.GetProperty("timezone").GetString() ?? ""; TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); DateTimeOffset cityTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, timeZone); // Format coordinates with a period decimal separator so the URL
// is culture-independent.
string latStr = latitude.ToString(CultureInfo.InvariantCulture); string lonStr = longitude.ToString(CultureInfo.InvariantCulture); // Request only the current measurements used in the weather response. string weatherUrl = $"https://api.open-meteo.com/v1/forecast"; weatherUrl += $"?latitude={latStr}&longitude={lonStr}"; weatherUrl += $"&current=temperature_2m,weather_code,wind_speed_10m&timezone=auto"; string weatherJson = await client.GetStringAsync(weatherUrl); using JsonDocument weatherDoc = JsonDocument.Parse(weatherJson); // Convert the selected forecast fields into the app's weather result. JsonElement current = weatherDoc.RootElement.GetProperty("current"); return new Weather { Latitude = latitude, Longitude = longitude, Temperature = current.GetProperty("temperature_2m").GetDouble(), WindSpeed = current.GetProperty("wind_speed_10m").GetDouble(), City = name, Country = country, Condition = TranslateWeatherCode(current.GetProperty("weather_code").GetInt32()), LocalTime = $"{cityTime:yyyy-MM-dd HH:mm:ss zzz}" }; } // Converts Open-Meteo weather codes into readable condition descriptions. static string TranslateWeatherCode(int code) => code switch { 0 => "Clear sky", 1 => "Mainly clear", 2 => "Partly cloudy", 3 => "Overcast", 45 or 48 => "Fog", 51 or 53 or 55 => "Drizzle", 61 or 63 or 65 => "Rain", 71 or 73 or 75 => "Snow", 80 or 81 or 82 => "Rain showers", 95 => "Thunderstorm", 96 or 99 => "Thunderstorm with hail", _ => "Unknown" }; // Stores the weather fields used to build the tool's text response. class Weather { public double Latitude { get; set; } public double Longitude { get; set; } public double Temperature { get; set; } public double WindSpeed { get; set; } public string? City { get; set; } public string? Country { get; set; } public string? Condition { get; set; } public string? LocalTime { get; set; } public override string ToString() { string str = $"Weather in {City}/{Country}: {Temperature}°C, "; str += $"{WindSpeed} km/h, "; str += $"{Condition}, "; str += $"Local Time: {LocalTime}"; return str; } } }

What is a tool?

A tool is a function that the AI agent can call when it needs information or needs to perform an action.

Examples include:

  • Get weather
  • Read a file
  • Query a database
  • Call a REST API

In the above code, our weather tool fetches weather information for a given city by making an API call to a real weather service.

Step 3: Define the tool

Register a callable tool. Replace the code in Program.cs with the following:

using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using WeatherAgent;

// Expose the weather lookup to the agent without requiring tool-use approval.
AIFunction weatherTool = CopilotTool.DefineTool( (string city) => WeatherTools.GetWeatherAsync(city), toolOptions: new CopilotToolOptions { SkipPermission = true, }, factoryOptions: new AIFunctionFactoryOptions { Name = "GetWeather", Description = "Returns weather information and local time for a city.", } );

Why is the description important?

The AI uses the description to decide:

  • When the tool should be used
  • What problem it solves
  • What input it expects

Good descriptions improve tool selection accuracy.

Step 4: Create the agent and register the tool

Configure the agent and register the tool with it:

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

// Limit the agent to GetWeather and instruct it to answer using only the tool's results.
AIAgent agent = copilotClient.AsAIAgent(
    new SessionConfig {
        Tools = [weatherTool],
        SystemMessage = new SystemMessageConfig {
            Mode = SystemMessageMode.Append,
            Content = """
            Always call GetWeather for weather and local time.
            Use only its returned information in your answer.
            If it fails, report the failure; do not guess.
            """
        }
    },
    name: "Weather Assistant"
);

As additional tools are added, the agent can perform more complex tasks. For example:

  • GetWindSpeed()
  • GenerateReport()
  • QueryDatabase()

Step 5: Send a prompt

User request:

// to choose Barcelona via command-line arguments: dotnet run Barcelona
string city = args.Length > 0 ? args[0] : "Vancouver";
string prompt = $"What is the weather in {city} and what time is it there?";

Execute the prompt:

// Run the agent asynchronously and print its response.
AgentResponse response = await agent.RunAsync(prompt); Console.WriteLine(response.Text);

Run the application with dotnet run. You should get this output:

Vancouver is **overcast**, **8.1°C**, with winds at **15.2 km/h**.

**Local time:** 16:05 -07:00.

Allow user to choose AI model

The SDK chooses a default AI model. The application can be extended to allow the user to choose another AI model.

Inside the Helpers folder, add a C# class named SelectionPrompt with this code:

namespace WeatherAgent.Helpers;

// Reads a numbered console selection and returns its zero-based index.
internal static class SelectionPrompt { internal static int ReadIndex(string prompt, int optionCount, int defaultIndex) { while (true) { Console.Write(prompt); var answer = Console.ReadLine()?.Trim(); // Use the default when input is blank or the input stream has ended.
if (string.IsNullOrEmpty(answer)) return defaultIndex;
// Displayed options are one-based; callers use zero-based indexes. if (int.TryParse(answer, out var selection) && selection >= 1 && selection <= optionCount) return selection - 1; Console.WriteLine($"Enter a number from 1 to {optionCount}."); } } }

Also in the Helpers folder, add a C# class named ModelSelector with this code:

using GitHub.Copilot;

namespace WeatherAgent.Helpers;

// Lists available Copilot models and prompts the user to select one. internal static class ModelSelector {
internal static async Task<string> PickAsync(CopilotClient client, string preferredModel) { // read all available models into a list
var models = (await client.ListModelsAsync()).ToList();
// Return an empty model ID when no models are available. if (models.Count == 0) return string.Empty; // Match the preferred model without requiring a specific letter case.
var defaultIndex = models.FindIndex(model => string.Equals(model.Id, preferredModel, StringComparison.OrdinalIgnoreCase)); // Use the preferred model when available; otherwise default to the first listed model. defaultIndex = defaultIndex >= 0 ? defaultIndex : 0; Console.WriteLine("Choose a Copilot model:"); for (var index = 0; index < models.Count; index++) { Console.WriteLine($" {index + 1}. {models[index].Id}"); } // Accept a numbered selection or use the displayed default for blank input.
var selectedIndex=SelectionPrompt.ReadIndex( $"Model [{defaultIndex + 1}]: ", models.Count, defaultIndex); return models[selectedIndex].Id; } }

The most important statement in the above code is the one that reads all available AI models into a list:

var models = (await client.ListModelsAsync()).ToList();

Let's use these helper methods in our app. In Program.cs, add this code right under the await copilotClient.StartAsync(); statement:

// the default model 'auto' will be used if no preference is specified
var model = await ModelSelector.PickAsync(copilotClient, "auto");

NOTE: Make sure you add this statement at the top of Program.cs:

using WeatherAgent.Helpers;

Also, in Program.cs, add this code inside the SessionConfig { . . . } block:

Model = model,

Run the app with dotnet run barcelona to see what it is like in Barcelona, Spain. You will be asked to choose a model. The number of displayed models depends on your subscription level with GitHub.

Choose a Copilot model:
  1. auto
  2. claude-sonnet-5.5
  3. claude-sonnet-5
  4. claude-fable-5.2
  5. claude-fable-5.1
  6. claude-fable-5
  7. claude-opus-5.5
  8. claude-opus-4.8-fast
  9. claude-haiku-5.5
  10. claude-haiku-4.5
  11. gpt-6.1-sol
  12. gpt-6.1-terra
  13. gpt-6-sol
Model [1]:

After entering 11 for gpt-6.1-sol, the result was:

Barcelona is **12°C and partly cloudy**, with winds of **5.8 km/h**.

The reported local time is **12:24 AM on November 24, 2026**.

Understanding what happens internally

Runtime workflow

  1. User Prompt
  2. Agent Analysis
  3. Tool Selection
  4. Tool Execution
  5. Response Generation

Agent reasoning

  1. User Prompt
  2. Need City Weather
  3. Call GetWeather()
  4. Generate Answer

The Copilot SDK provides the orchestration layer that performs this workflow.

Conclusion

In this tutorial, we built a .NET weather assistant with the GitHub Copilot SDK, registered a tool the agent can call, and added a model-selection step. The example uses hard-coded weather data, but you can extend the same pattern to call a real weather API or connect other tools. As you do, handle API errors and credentials securely. With the SDK coordinating prompts and tool calls, you can focus on the capabilities your assistant provides.

Monday, November 16, 2026

Develop a smart blazor app that uses GitHub Copilot SDK

In this tutorial, we will build a Blazor application that uses the GitHub Copilot SDK and custom tools to work with a SQLite database of sample students. For example, you can ask: What is the status of student 76?

Along the way, you will learn how to:

  1. Create a Blazor project and configure a SQLite database.
  2. Write database-backed tools and register them with a Copilot session.
  3. Send prompts from a Blazor page and display responses.
  4. Observe tool calls and identify opportunities to improve them.

Demo only: We will use fictional student data and a local development environment. The example can change a student record and automatically approves permission requests.

Agent workflow

Blazor UI → AgentService → Copilot session → student tool → SQLite → Response

The page sends a prompt to the service. The model may select a registered tool; the SDK invokes its C# handler, which uses Entity Framework Core to query or update SQLite. The tool result is returned to the model to help it compose a response. Tool selection and generated answers can vary.

Prerequisites

  • .NET 10 SDK or later and Visual Studio Code with the C# Dev Kit extension.
  • A GitHub account with access to GitHub Copilot, including the Free plan where available.
  • Internet access for package installation, Copilot, and the students sample-data endpoint used during migrations and model initialization.
  • The dotnet-ef tool, installed in Step 5 if needed.

Check your .NET SDK with: dotnet --list-sdks.

Step 1: Create the Blazor project

In a working directory, create the application and add the required packages:

dotnet new blazor -o AI4SchoolAgent
cd AI4SchoolAgent
mkdir Models
mkdir Data
mkdir Services
mkdir Tools
dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Sqlite

SQLite: No separate SQLite installation or database server is required. The Microsoft.EntityFrameworkCore.Sqlite package installed in Step 1 includes the SQLite dependencies. Step 5 creates the database file automatically. A SQLite viewer is optional if you want to inspect the data.

Step 2: Configure the SQLite database

Open the AI4SchoolAgent folder in Visual Studio Code. Create Models/Student.cs with the following code:

using System.ComponentModel.DataAnnotations;

namespace AI4SchoolAgent.Models;

public class Student {

    public int StudentId { get; set; }

    [Required]
    public String? FirstName { get; set; }

    [Required]
    public String? LastName { get; set; }

    [Required]
    public String? School { get; set; }

    [Required]
    public String? Gender { get; set; }

    public DateOnly? DateOfBirth { get; set; }
    public String? Status { get; set; }
}

Entity Framework Core uses a database context to map the student model to SQLite. Create Data/SchoolDbContext.cs:

using AI4SchoolAgent.Models;
using Microsoft.EntityFrameworkCore;

namespace AI4SchoolAgent.Data;

public class SchoolDbContext : DbContext {
  public DbSet<Student> Students => Set<Student>();

  public SchoolDbContext(DbContextOptions<SchoolDbContext> options) : base(options) { }

  protected override void OnModelCreating(ModelBuilder modelBuilder) {
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Student>().HasData(GetStudents());

  }

  private static IEnumerable<Student> GetStudents() {
    const string studentsUrl =
      "https://gist.githubusercontent.com/medhatelmasry/2ae7a36d5392f862b0d1039b2a52b9b4/raw/45533eda6c43ce439dbc65c37a7fbdef01546c2d/students.json";

    using var httpClient = new HttpClient();

    var json = httpClient.GetStringAsync(studentsUrl).GetAwaiter().GetResult();

    return System.Text.Json.JsonSerializer.Deserialize<List<Student>>(json)

      ?? throw new InvalidOperationException("The students JSON returned no data.");
  }
}

The database context class reads sample students from a JSON endpoint. The data is captured in the migration and inserted when it is applied. Model initialization also fetches the endpoint, so it must remain reachable; this network-dependent approach is for the tutorial, not production seeding.

Add the following property inside the existing top-level JSON object in appsettings.json, with commas separating it from neighboring properties:

"ConnectionStrings": {
  "DefaultConnection": "DataSource=school-db.sqlite;Cache=Shared;"
}

Step 3: Build the student tools

A tool is a C# function the agent can call to retrieve information or perform an action. These tools look up students by ID, school, or gender, list students with calculated ages, and initiate a withdrawal. The age tool returns all students with their ages.

Create Tools/StudentsAgentTools.cs:

using System.Text;
using AI4SchoolAgent.Models;
using Microsoft.EntityFrameworkCore;

namespace AI4SchoolAgent.Tools;

// Provides database-backed operations for querying and updating student records.
public class StudentsAgentTools {
    private readonly DbContext _dbContext;

    // Initializes a new instance of the StudentsAgentTools class.
    public StudentsAgentTools(DbContext dbContext) {
        _dbContext = dbContext;
    }

    // Retrieves a student's details by its unique identifier.
    public async Task<string> GetStudentDetailsByIdAsync(int studentId) {
        var student = await _dbContext.Set<Student>().FindAsync(studentId);

        return student != null

            ? $"Student {studentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}"

            : "Student not found.";
    }

    // Retrieves students whose gender matches the specified value.
    public async Task<string> GetStudentsByGenderAsync(string gender) {
        var students = await _dbContext.Set<Student>().Where(s => s.Gender == gender).ToListAsync();

        if (students.Count == 0)
            return "No students found.";

        var result = new StringBuilder();

        foreach (var student in students) {
            result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}");
        }
        return result.ToString();
    }
// Retrieves students enrolled at the specified school. public async Task<string> GetStudentsBySchoolAsync(string school) { var students = await _dbContext.Set<Student>().Where(s => s.School == school).ToListAsync(); if (students.Count == 0) return "No students found."; var result = new StringBuilder(); foreach (var student in students) { result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}"); } return result.ToString(); } // Retrieves all students with their birth date and calculated age. public async Task<string> GetStudentsByAgeAsync() { var students = await _dbContext.Set<Student>().ToListAsync(); if (students.Count == 0) return "No students found."; var result = new StringBuilder(); foreach (var student in students) { var today = DateOnly.FromDateTime(DateTime.Today); var age = student.DateOfBirth is { } dateOfBirth ? today.Year - dateOfBirth.Year - (today < dateOfBirth.AddYears(today.Year - dateOfBirth.Year) ? 1 : 0) : (int?)null; result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Born: {student.DateOfBirth?.ToString("yyyy-MM-dd") ?? "not recorded"}, Age: {age?.ToString() ?? "not recorded"}"); } return result.ToString(); } // Retrieves details for every student in the database. public async Task<string> GetAllStudentsAsync() { var students = await _dbContext.Set<Student>().ToListAsync(); if (students.Count == 0) return "No students found."; var result = new StringBuilder(); foreach (var student in students) { result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}"); } return result.ToString(); } // Initiates the withdrawal process for a student. public async Task<string> ProcessWithdrawalAsync(int studentId, string reason) { var student = await _dbContext.Set<Student>().FindAsync(studentId); if (student == null) return "Student not found."; // Record the withdrawal state on the student until a formal workflow is added. student.Status = "Withdrawal Initiated"; await _dbContext.SaveChangesAsync(); return $"Withdrawal initiated for student {studentId}."; } }

Most tools return formatted text to the model. ProcessWithdrawalAsync instead changes the student's status to Withdrawal Initiated. It accepts a reason but does not perform a complete withdrawal workflow.

Step 4: Create the agent service and register the tools

CopilotClient connects the application to the GitHub Copilot SDK. A CopilotSession holds the configuration for a conversation, including its model and available tools. Here, AIFunctionFactory.Create wraps each C# method with a name, parameters, and description that help the model decide when to call it. Clear, specific descriptions improve tool selection but do not guarantee it.

Create Services/AgentService.cs and add this C# code to it:

using System.Text;
using AI4SchoolAgent.Data;
using AI4SchoolAgent.Tools;
using GitHub.Copilot;
using Microsoft.Extensions.AI;

namespace AI4SchoolAgent.Services;

// Coordinates Copilot sessions and exposes student-related tools to answer prompts.
public class AgentService {
  private readonly SchoolDbContext _db;
  private readonly ILogger<AgentService> _logger;

  // Initialize a new instance of the AgentService class.
  public AgentService(SchoolDbContext db, ILogger<AgentService> logger) {
    _logger = logger;
    _db = db;
  }

  // Sends a prompt to a Copilot session configured with the available student tools.
  public async Task<string> AskAsync(string prompt) {
// Create a Copilot client and start the local session infrastructure. await using var client = new CopilotClient( new CopilotClientOptions { LogLevel = CopilotLogLevel.Info }); await client.StartAsync(); var toolService = new StudentsAgentTools(_db); // Register database operations as tools that Copilot can invoke. var tools = new List<AIFunctionDeclaration> { AIFunctionFactory.Create( async (int studentId) => await toolService.GetStudentDetailsByIdAsync(studentId), "get_student_details", "Look up student details."), AIFunctionFactory.Create( async (int studentId, string reason) => await toolService.ProcessWithdrawalAsync(studentId, reason), "process_withdrawal", "Process a withdrawal request."), AIFunctionFactory.Create( async (string gender) => await toolService.GetStudentsByGenderAsync(gender), "get_students_by_gender", "Find students by gender"), AIFunctionFactory.Create( async (string school) => await toolService.GetStudentsBySchoolAsync(school), "get_students_by_school", "Find students by school"), AIFunctionFactory.Create( async () => await toolService.GetStudentsByAgeAsync(), "get_students_by_age", "Find students by age"), AIFunctionFactory.Create( async () => await toolService.GetAllStudentsAsync(), "get_all_students", "Get all students") }; // Allow tool execution automatically and use the default model selection. var config = new SessionConfig { Model = "auto", OnPermissionRequest = PermissionHandler.ApproveAll, Tools = tools }; await using var session = await client.CreateSessionAsync(config); var responseBuilder = new StringBuilder(); // Complete only after the session reports that it is idle. var tcs = new TaskCompletionSource<string>(); session.On<SessionEvent>(evt => { switch (evt) { case AssistantMessageEvent msg: responseBuilder.Append(msg.Data.Content); break; case SessionIdleEvent: tcs.SetResult(responseBuilder.ToString()); break; case ToolExecutionStartEvent tool: _logger.LogInformation( "Executing tool: {ToolName}", tool.Data.ToolName); break; } }); await session.SendAsync(new MessageOptions { Prompt = prompt }); return await tcs.Task.WaitAsync(TimeSpan.FromSeconds(30)); } }

Understanding the session events

After sending a prompt, the handler collects AssistantMessageEvent content and logs ToolExecutionStartEvent tool names. It completes when SessionIdleEvent arrives, or raises a timeout after 30 seconds. This is not a token-by-token streaming UI. The service creates a new client and session for every prompt, so the displayed messages are only UI history: follow-up prompts do not automatically include earlier messages.

Permission and data warning: PermissionHandler.ApproveAll automatically approves permission requests; it is not user authorization or confirmation for a database change. The tool handler itself writes to SQLite. Before using a real database, add authenticated users, server-side authorization, explicit confirmation for writes, auditing, and appropriate controls for student data sent to the model. Review the SDK's deployment and data-handling requirements and avoid logging sensitive data.

Step 5: Register services and create the database

At the top of Program.cs, add these imports:

using AI4SchoolAgent.Data;
using AI4SchoolAgent.Services;
using Microsoft.EntityFrameworkCore;

Add these services just before the var app = builder.Build(); statement:

// Register school DB context and configure it to use SQLite connection string.
builder.Services.AddDbContext<SchoolDbContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"))
); // Register AgentService with a scoped lifetime.
builder.Services.AddScoped<AgentService>();

Database migrations

Check whether dotnet ef --version reports a version. If the tool is not installed, globally install it on your computer with this terminal window command:

dotnet tool install -g dotnet-ef

From the project root, create a migration by running the following terminal window command:

dotnet ef migrations add M1 -o Data/Migrations

To programatically create the database and apply migrations, add the following code to Program.cs just before the app.Run(); statement. This will create the database with sample student data, if it does not already exist.

using (var scope = app.Services.CreateScope()) {
   var services = scope.ServiceProvider;
   var context = services.GetRequiredService<SchoolDbContext>();
   context.Database.Migrate();
}

Once you start the web app in step 7 (later), the migration creates school-db.sqlite and inserts the sample students. If the JSON endpoint is unavailable, the migration or model initialization can fail; check your network connection and the endpoint before retrying.

Step 6: Build the Blazor interface

We will create a blazor component page that sends each prompt to AgentService, displays a busy indicator while it waits, and shows either the response or an error.

Replace content of existing Components/Pages/Home.razor with:

@page "/"
@rendermode InteractiveServer
@inject AI4SchoolAgent.Services.AgentService AgentService

<PageTitle>School AI Agent</PageTitle>

<h3>School Administration AI Agent</h3>

@if (IsBusy) {
    <p class="alert alert-info mt-3" role="status">Thinking...</p>
}

<div class="chat-window">
    @foreach (var message in Messages) {
        <div class="message">
            <b>@message.Role:</b>
            <div>@message.Content</div>
        </div>
    }
</div>

<div class="mt-3">
    <InputTextArea class="form-control" rows="4" @bind-Value="Prompt" />

    <button class="btn btn-primary mt-2" @onclick="SendPrompt" disabled="@IsBusy">
        Ask Agent
    </button>
</div>

@if (!string.IsNullOrEmpty(ErrorMessage)) {
    <div class="alert alert-danger mt-3" role="alert">@ErrorMessage</div>
}

@code {
    string Prompt = "";
    bool IsBusy;
    string? ErrorMessage;
    List<ChatMessage> Messages = new();

    async Task SendPrompt() {
        if (string.IsNullOrWhiteSpace(Prompt))
            return;

        Messages.Add(new ChatMessage {
            Role = "User",
            Content = Prompt
        });

        IsBusy = true;
        ErrorMessage = null;

        try {
            var result = await AgentService.AskAsync(Prompt);

            Messages.Add(new ChatMessage {
                Role = "Agent",
                Content = result
            });

            Prompt = "";
        } catch (Exception ex) {
            ErrorMessage = $"Unable to get a response: {ex.Message}";
        } finally {
            IsBusy = false;
        }
    }

    class ChatMessage {
        public string Role { get; set; } = "";
        public string Content { get; set; } = "";
    }
}

Add styling to a new file Components/Pages/Home.razor.css:

.chat-window {
    border: 1px solid #ddd;
    height: 400px;
    overflow-y: auto;
    padding: 10px;
    background-color: #fafafa;
}

.message {
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 6px;
    background-color: white;
}

Step 7: Run and test the application

From the project root, run:

dotnet watch

The web app will automatically open in your default browser. Start with a read-only prompt:

What is the status of student 76?

A successful answer identifies the student and their recorded status, or says that no status is recorded. The wording can vary. Check the terminal for a tool call such as:

Entity Framework may also log the SQL query in the terminal window. The model may select a different tool or produce a different answer, so verify results against the sample database rather than treating generated answers as guaranteed facts. These screenshots show example interactions:

Try more read-only prompts, such as:

  • Who is the oldest student in medicine? 
  • Who is the youngest student in mining?
  • List all male students studying nursing.
  • Count students in each school.

To try the write tool with the sample data, ask Initiate withdrawal for student 76 because they are no longer enrolled, then ask for that student's status in a separate prompt. This changes the local database immediately. Each prompt is independent, so include the student ID in both.

For the count question, observe how many tools and SQL queries are used. In one run, the agent called get_students_by_school five times, producing the logs below. Tool selection and query counts can vary between runs.

info: AI4SchoolAgent.Services.AgentService[0]
      Executing tool: get_students_by_school
info: AI4SchoolAgent.Services.AgentService[0]
      Executing tool: get_students_by_school
info: AI4SchoolAgent.Services.AgentService[0]
      Executing tool: get_students_by_school
info: AI4SchoolAgent.Services.AgentService[0]
      Executing tool: get_students_by_school
info: AI4SchoolAgent.Services.AgentService[0]
      Executing tool: get_students_by_school
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[@school='?' (Size = 7)], CommandType='Text', CommandTimeout='30']
      SELECT "s"."StudentId", "s"."DateOfBirth", "s"."FirstName", "s"."Gender", "s"."LastName", "s"."School", "s"."Status"
      FROM "Students" AS "s"
      WHERE "s"."School" = @school
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[@school='?' (Size = 6)], CommandType='Text', CommandTimeout='30']
      SELECT "s"."StudentId", "s"."DateOfBirth", "s"."FirstName", "s"."Gender", "s"."LastName", "s"."School", "s"."Status"
      FROM "Students" AS "s"
      WHERE "s"."School" = @school
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[@school='?' (Size = 9)], CommandType='Text', CommandTimeout='30']
      SELECT "s"."StudentId", "s"."DateOfBirth", "s"."FirstName", "s"."Gender", "s"."LastName", "s"."School", "s"."Status"
      FROM "Students" AS "s"
      WHERE "s"."School" = @school
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[@school='?' (Size = 8)], CommandType='Text', CommandTimeout='30']
      SELECT "s"."StudentId", "s"."DateOfBirth", "s"."FirstName", "s"."Gender", "s"."LastName", "s"."School", "s"."Status"
      FROM "Students" AS "s"
      WHERE "s"."School" = @school
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[@school='?' (Size = 8)], CommandType='Text', CommandTimeout='30']
      SELECT "s"."StudentId", "s"."DateOfBirth", "s"."FirstName", "s"."Gender", "s"."LastName", "s"."School", "s"."Status"
      FROM "Students" AS "s"
      WHERE "s"."School" = @school

Troubleshooting

  • Missing types or namespaces: Check the filenames, namespaces, imports, and package installation commands. Run dotnet build from the project root to see the compiler errors.
  • Migration or database error: Check the EF package and tool versions, connection string, working directory, and access to the sample JSON endpoint. Run both migration commands from the project root.
  • Timeout or unexpected response: Check the terminal for errors and tool calls, confirm network connectivity, and retry a specific prompt. The example waits up to 30 seconds; model responses and tool selection are not deterministic.

Deployment considerations

Before deploying the assistant, decide how it will authenticate and where model inference will run. Common options include:

  1. Fine-grained personal access token: Use a narrowly scoped token for a controlled deployment, and store and rotate it securely.
  2. GitHub OAuth: For an app used by people with Copilot accounts, let each user sign in with GitHub and provide their own token to the SDK rather than sharing credentials.
  3. Azure-hosted model: For a school application, consider an Azure-hosted model instead of GitHub-hosted Copilot inference. This means configuring the app for the chosen Azure model and securing its access.

Choose the approach that fits your users, access requirements, and hosting environment. Never hard-code tokens or commit them to source control.

To implement option 1 above: 

1) Create fine-grained personal access token token on GitHub.com with Copilot Requests permission.

2) Set  GetHubToken and UseLoggedInUser options as follows:

new CopilotClientOptions { 
  LogLevel = CopilotLogLevel.Info,
  GitHubToken = Environment.GetEnvironmentVariable("COPILOT_GITHUB_TOKEN"),
  UseLoggedInUser = false
}

3) Set environment variable: COPILOT_GITHUB_TOKEN=github_pat_xxxxxxxx

Next steps

For an optimization exercise, add a read-only tool that groups students by school and returns counts directly from SQLite. Compare its query and output with those produced for the count prompt above. You can also explore preserving a session across messages, with appropriate per-user isolation and resource cleanup.

Before deployment, replace the demo's automatic permissions and unconfirmed writes with an appropriate authorization and confirmation workflow. Protect credentials, minimize data sent to the model, and review privacy, logging, and hosting requirements.

Conclusion

We built a Blazor interface that sends prompts to a Copilot session with database-backed tools. The SDK coordinates tool calls, while the C# handlers access SQLite. This sample starts a new session for each prompt and needs additional safeguards before it can be used beyond a local demonstration.

Monday, November 9, 2026

Scaffold Interactive-Server Blazor CRUD pages with SQLite

In this walkthrough, we will use the scaffolding tool to create the CRUD pages for a data driven Interactive-Server Blazor app. The app connects directly with SQLite database using Entity Framework Core.

Overview

Blazor is a framework for developing interactive client-side web applications using C# instead of JavaScript.

Architecture

The architecture of the application that we will be building will look like this: 

ASP.NET Core hosts the server-side app and sets up SignalR endpoints where clients connect. SignalR is responsible for updating the DOM on the client with any changes. The Blazor application on the server connects directly to the database using Entity Framework Core.

Blazor Render Modes

NameDescriptionRender LocationInteractive
Static ServerStatic server-side rendering (static SSR)Server❌
Interactive ServerInteractive server-side rendering (interactive SSR) using Blazor Server.Server✔️
Interactive WASMClient-side rendering (CSR) using Blazor WebAssembly.Client✔️
Interactive AutoInteractive SSR using Blazor Server initially and then CSR on subsequent visits after the Blazor bundle is downloaded.Server, then client✔️

To apply a render mode to a component, use the @rendermode directive on the component instance or on the component definition. Example:

<Dialog @rendermode="InteractiveServer" />

In this post, we will build a Server-side Blazor app talks directly to a SQLite database. This is a very realistic option since both blazor and the database server run on the server.

Let's get coding

In a terminal window, go to a work directory. Enter the following command to create a Server-Side Blazor application inside a directory named BlazorEF: 

dotnet new blazor -o BlazorEF
cd BlazorEF
mkdir Models
mkdir Data

Open the BlazorEF folder in Visual Studio Code.

When you run the app, your default browser will load a page that looks like this: 

We will extend the above application so that it talks to SQLite using Entity Framework Core. To this end, we will be dealing with a very simple Student model. Therefore, add a Student.cs class file to the Models folder with the following C# content: 

public class Student {
    public int StudentId { get; set; }

    [Required]
    public String? FirstName { get; set; }

    [Required]
    public String? LastName { get; set; }

    [Required]
    public String? School { get; set; }

    [Required]
    public String? Gender { get; set; }

    public DateOnly? DateOfBirth { get; set; }
}

Since we will be using SQLite, we will need to add the appropriate Entity Framework Core packages to our project. From within a terminal window at the root of your BlazorEF project, run the following commands to add the appropriate database related packages: 

dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

We need to add a connection string for the SQLite database. Add the following to the appsettings.json file: 

"ConnectionStrings": {
  "DefaultConnection": "DataSource=college.db;Cache=Shared;"
}

We will be using the Entity Framework Code First approach. 

Developers prefer having sample data when building data driven applications. Therefore, we will create some sample data to ensure that our application behaves as expected. Student data from this link will be used.

The starting point is to create a database context class. Add a C# class file named SchoolDbContext.cs in the Data folder with the following C# code: 

public class SchoolDbContext : DbContext {
    public DbSet<Student> Students => Set<Student>();

    public SchoolDbContext(DbContextOptions<SchoolDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Student>().HasData(GetStudents());
    }

    private static IEnumerable<Student> GetStudents() {
        const string studentsUrl =
            "https://gist.githubusercontent.com/medhatelmasry/2ae7a36d5392f862b0d1039b2a52b9b4/raw/45533eda6c43ce439dbc65c37a7fbdef01546c2d/students.json";

        using var httpClient = new HttpClient();

        var json = httpClient.GetStringAsync(studentsUrl).GetAwaiter().GetResult();

        return System.Text.Json.JsonSerializer.Deserialize<List<Student>>(json)
            ?? throw new InvalidOperationException("The students JSON returned no data.");
    }
}

Notice the above code will seed Student data into the database.

In the Program.cs file, just before ‘var app = builder.Build();’, add the following code so that our application can use SQLite:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<SchoolDbContext>(
    options => options.UseSqlite(connectionString)
);

We are now ready to apply Entity Framework migrations, create the database and seed data. If you have not done so already, you will need to globally install the Entity Framework CLI tool. This tooling is installed globally on your computer by running the following command in a terminal window:

dotnet tool install --global dotnet-ef

To make sure nothing is broken, build your project with "dotnet build" before proceeding. Then, from within a terminal window inside the BlazorEF root directory, run the following command to create migrations: 

dotnet ef migrations add M1 -o Data/Migrations

 This results in the creation of a migration file ending with the name ....M1.cs in the Data/Migrations folder. In my case, this file looked like this: 

Note that the above code also includes commands for inserting sample data.

The next step is to create the SQLite college.db database file. To automatically apply migrations, add the following code to Program.cs, right before the final app.Run() statement:

using (var scope = app.Services.CreateScope()) {
  var services = scope.ServiceProvider;

  var context = services.GetRequiredService<SchoolDbContext>();    

  context.Database.Migrate();
}

We will scaffold the CRUD pages for students using the scaffold tool. To install the scaffold tool globally, enter this command in any terminal window:

dotnet tool install --global Microsoft.dotnet-scaffold

Thereafter, run the scaffold tool in the root folder of your Blazor project with:

dotnet scaffold 

Follow these steps:

Delete this unnecessary addition in the appsettings.json file:

"SchoolDbContext": "Data Source=SchoolDbContext.db"

You will notice these razor components have been added to your Blazor project:

Add this menu item to your Components/Layout/NavMenu.razor file.

<div class="nav-item px-3">
    <NavLink class="nav-link" href="students">
        <span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Students
    </NavLink>
</div>

Run your application:

You will discover that Student CRUD operations work seamlessly.

I hope you learned something new in this tutorial and trust that you will build much more sophisticated Blazor apps than this.

Monday, October 12, 2026

Seed & Extend Identity Users & Roles in ASP.NET with Scaffold tool

In this tutorial, we will learn how to add more data fields to the standard ASP.NET users & roles schema using the scaffold tool. We will also learn how to seed users and roles.

Prerequisites

To proceed with this tutorial, you need the following:

  • VS Code
  • .NET: The current version of .NET is 10.0
  • the dotnet-ef tool
  • Tthe Microsoft.dotnet-scaffold tool

Getting Started

Create a new razor pages application with the following terminal window command:

dotnet new razor --auth individual -o XtendUsersRoles
cd XtendUsersRoles
mkdir Models

This creates an ASP.NET app that uses SQLite database for authentication.

Open the application folder in VS Code.

Suppose we want to capture more data about the user, in addition to email and password. Keeping it simple, lwe will extend user data with FirstName & LastName.

An easy way to do this is to create a new class that extends IdentityUser and adds FirstName and LastName properties. In the Models folder, add a new class named XUser to it with the following class code: 

public class XUser : IdentityUser {
  public XUser() : base() { }

  public string? FirstName { get; set; }
  public string? LastName { get; set; }
}

We may also wish to extend the standard roles table with a CreatedDate property.

Just as we did with users, we will create another class for roles that inherits from IdentityRole. In the Models folder, add another class named XRole and add to it the following code:

public class XRole: IdentityRole {

  public XRole() : base() { }

  public XRole(string roleName) : base(roleName) { }

  public DateTime CreatedDate { get; set; }
}

Add the following to Pages/_ViewImports.cshtml:

@using XtendUsersRoles.Models

Edit Data/ApplicationDbContext.cs file and make ApplicationDbContext  inherit from IdentityDbContext<XUser, XRole, string>(options). The ApplicationDbContext class code will look like this:

public class ApplicationDbContext(
    DbContextOptions<ApplicationDbContext> options)
    : IdentityDbContext<XUser, XRole, string>(options)
{

}

Add these passwords to the appsettings.Development.json file:

"Passwords": {
  "Admin": "P@$$w0rd",
  "Member": "P@$$w0rd"
}

We will seed the database with two roles and two users. Add Data/IdentitySeeder.cs with the following code:

public static class IdentitySeeder {
  public static async Task SeedAsync(
      UserManager<XUser> userManager,
      RoleManager<XRole> roleManager,
      IConfiguration configuration) {

      ArgumentNullException.ThrowIfNull(userManager);
      ArgumentNullException.ThrowIfNull(roleManager);
      ArgumentNullException.ThrowIfNull(configuration);

      await EnsureRoleAsync(roleManager, "Admin");
      await EnsureRoleAsync(roleManager, "Member");

      await EnsureUserAsync(
          userManager, configuration["Passwords:Admin"]!, "aa@aa.aa", "Adam", "Atkins", "Admin");

      await EnsureUserAsync(

          userManager, configuration["Passwords:Member"]!, "mm@mm.mm", "Mike", "Moore", "Member");
  }

  private static async Task EnsureRoleAsync(RoleManager<XRole> roleManager, string roleName) {
      if (!await roleManager.RoleExistsAsync(roleName)) {
          var result = await roleManager.CreateAsync(new XRole(roleName) {
              CreatedDate = DateTime.UtcNow
          });

          EnsureSucceeded(result, $"creating role '{roleName}'");
      }
  }

  private static async Task EnsureUserAsync(
      UserManager<XUser> userManager,
      string password,
      string email,
      string firstName,
      string lastName,
      string roleName) {

      var user = await userManager.FindByEmailAsync(email);

      if (user is null) {
          user = new XUser {
              UserName = email,
              Email = email,
              EmailConfirmed = true,
              FirstName = firstName,
              LastName = lastName
          };

          var result = await userManager.CreateAsync(user, password);
          EnsureSucceeded(result, $"creating user '{email}'");
      }

      if (!await userManager.IsInRoleAsync(user, roleName)) {
          var result = await userManager.AddToRoleAsync(user, roleName);
          EnsureSucceeded(result, $"adding user '{email}' to role '{roleName}'");
      }

  }

  private static void EnsureSucceeded(IdentityResult result, string operation) {
      if (!result.Succeeded) {
          var errors = string.Join("; ", result.Errors.Select(error => $"{error.Code}: {error.Description}"));

          throw new InvalidOperationException($"Identity seeding failed while {operation}: {errors}");
      }
  }
}

In the Program.cs, replace the builder.Services.AddDefaultIdentity. . .  statement with this:

builder.Services.AddIdentity<XUser, XRole>(
options => {
    options.Stores.MaxLengthForKeys = 128;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddRoles<XRole>();

We need to call the identity seed logic from somewhere. In Program.cs, Add the following code to the “if (app.Environment.IsDevelopment())” block, right before “app.UseMigrationsEndPoint()”:

await using var scope = app.Services.CreateAsyncScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await dbContext.Database.MigrateAsync();

await IdentitySeeder.SeedAsync(
    scope.ServiceProvider.GetRequiredService<UserManager<XUser>>(),
    scope.ServiceProvider.GetRequiredService<RoleManager<XRole>>(),
    app.Configuration);

Edit Pages/Shared/_LoginPartial.cshtml and change:

@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

TO

@inject SignInManager<XUser> SignInManager
@inject UserManager<XUser> UserManager

Let us start with a clean database and migration. Therefore, delete app.db and the Data/Migrations folder. 

If you do not already have the .NET entity framework tool, execute the following command from within a terminal window:

dotnet tool install -g dotnet-ef

Then, execute the following entity framework migration commands from within a terminal window in the root folder of the application:

dotnet ef migrations add M1 -o Data/Migrations
dotnet ef database update

To seed the database with sample roles and users, start the application with:

dotnet watch

To prove that user and role data are successfully seeded, login with one of the below credentials that were previously seeded:

EmailPassword
aa@aa.aa P@$$w0rd
mm@mm.mm P@$$w0rd

The next task we need to accomplish is to modify the registration page so that the application can capture extended data such as FirstName & LastName. ASP.NET provides ASP.NET Core Identity as a Razor Class Library. This means that the registration UI is baked into the assemblies and is surfaced with the .AddDefaultUI() option with the services.AddIdentity() command in Program.cs.

If you do not already have the .NET scaffolding tool, execute the following command from within a terminal window:

dotnet tool install -g Microsoft.dotnet-scaffold

To expose the identity pages (like LOgin, Register, Logout, etc) and change them, we will use the Scaffold tool. Run the following command from within a terminal window at the root of your project:

dotnet scaffold

Follow these steps to generate the Identity razor pages:


The result of the scaffolding process is that we now have a new folder /Areas/Identity/Pages/Account with many pages that pertains to Identity:

There are, however, some things that the scaffold tool did incorrectly:

  1. It added an ApplicationDbContext connection string in appsettings.json file. Go ahead and delete it.
  2. The scaffold tool also added this line of code into Program.cs, that also needs to be deleted:

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>();

Edit the code-behind file Areas/Identity/Pages/Account/Register.cshtml.cs. Add the following properties to the InputModel class: 

[Required]
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)]
[Display(Name = "First Name")]
public string? FirstName { get; set; }

[Required]
[DataType(DataType.Text)]
[StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)]
[Display(Name = "Last Name")]
public string? LastName { get; set; }

In the same file, delete the CreateUser() method.

In the OnPostAsync() method at around line 128, replace:

var user = CreateUser();

with: 

var user = new XUser {
  UserName = Input.Email,
  Email = Input.Email,
  FirstName = Input.FirstName,
  LastName = Input.LastName
};

In the same Register.cshtml.cs file, replace all instances of ApplicationUser with XUser. Do this also in files Login.cshtml.cs and Logout.cshtml.cs.

Next, let us update the UI. Edit razor page Areas\Identity\Pages\Account\Register.cshtml. Add the following markup to the form right before the email/username block: 

<div class="form-floating mb-3">
    <input asp-for="Input.FirstName" class="form-control" aria-required="true" placeholder="first name" />
    <label asp-for="Input.FirstName">First Name</label>
    <span asp-validation-for="Input.FirstName" class="text-danger"></span>
</div>

<div class="form-floating mb-3">
    <input asp-for="Input.LastName" class="form-control" aria-required="true" placeholder="last name" />
    <label asp-for="Input.LastName">Last Name</label>
    <span asp-validation-for="Input.LastName" class="text-danger"></span>
</div>

Run the web application and click on the Register button on the top-right side.


After you click on Register, all user data will be saved in the database. We can capture first name and last name as expected. 

We have succeeded in updating the registration page so that additional user data can be captured. Mission accomplished.

Monday, October 5, 2026

ASP.NET 10.0 Minimal WebAPI with SQLite & Swagger

This tutorial is about using ASP.NET 10.0 Minimal WebAPI. We will build a simple application with SQLite to save students data. We will then consume the API from an HTML page and add a Swagger interface to test the API endpoints.

Requirements:

  • .NET 10.0
  • C# Dev Kit VS Code Extenstion

In a suitable working directory, create a Web API web application in the terminal window with:

dotnet new webapi -o StudentsMinApi 
cd StudentsMinApi
mkdir Data
mkdir Models
mkdir wwwroot code . dotnet watch

This will appear in your terminal window:

Point your browser to the URL displayed in the terminal window, followed by /weatherforecast.

In the above case the address would be http://localhost:5130/weatherforecast. This would display the following in your browser:

Look at the API code in Program.cs:

app.MapGet("/weatherforecast", () => {
    var forecast =  Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

Add this Entity Framework tool if you do not already have it: 

dotnet tool install --global dotnet-ef 

Let us add these packages that provide support for SQLite and Swagger: 

dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SQLite
dotnet add package Microsoft.EntityFrameworkCore.SQLite.Design
dotnet add package Swashbuckle.AspNetCore

Inside the Models folder, add the following Student class: 

public class Student {
    public int StudentId { get; set; }
    public string? LastName { get; set; }
    public string? FirstName { get; set; }
    public string? School { get; set; }
    public string? Gender { get; set; }
    public DateTime? DateOfBirth { get; set; }
}

Developers prefer having sample data when building data driven applications. Therefore, we will create some sample data to ensure that our application behaves as expected. Copy the following data from https://gist.github.com/medhatelmasry/2ae7a36d5392f862b0d1039b2a52b9b4 and save it into a text file wwwroot/students.csv.

Add the following connection string to your  appsettings.json file:

"ConnectionStrings": {
  "DefaultConnection": "DataSource=school.db;cache=shared;"
},

Next, we need to add an Entity Framework context class. Inside the Data folder, add a class file named ApplicationDbContext with the following content: 

public class ApplicationDbContext : DbContext {

    public DbSet<tudent> Students => Set<Student>();

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Student>().HasData(GetStudents());
    }

    private static IEnumerable<Student> GetStudents() {
        string[] p = { Directory.GetCurrentDirectory(), "wwwroot", "students.json" };
        var filePath = Path.Combine(p);

        var json = File.ReadAllText(filePath);
        var data = System.Text.Json.JsonSerializer.Deserialize<List<Student>>(json) ?? new List<Student>();

        return data;
    }

}

In the above code, student data is being seeded in the OnModelCreating() method by reading contents of students.json file.

We need to register the context class (ApplicationDbContext) with dependency injection in Program.cs. Add the following code right before “var app = builder.Build();” in Program.cs: 

var connStr = builder.Configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");

builder.Services.AddDbContext<ApplicationDbContext>(option => option.UseSqlite(connStr));

Let us add a migration and subsequently update the database. Execute the following CLI commands in a terminal window:

dotnet ef migrations add M1 -o Data/Migrations
dotnet ef database update

At this point the database and tables are created.

Students API

Let us add API endpoints that:

  • Read all the students
  • Read student data by id
  • Add student data
  • Update student data
  • Delete student data

This can easily be done using the scaffold tool. Make sure you install the tool globally with this terminal window command:

dotnet tool install --global Microsoft.dotnet-scaffold

Once you have installed the scaffold tool, enter the following command to start the tool at the root of your project:

dotnet scaffold

Make the choices as shown in the various steps below:

 

A file named StudentsApi.cs gets created in the root folder of your project with this code:

using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using StudentsMinApi.Data;
using StudentsMinApi.Models;

public static class StudentsApi {
    public static void MapStudentEndpoints(this IEndpointRouteBuilder routes) {
        var group = routes.MapGroup("/api/Student").WithTags(nameof(Student));

        group.MapGet("/", async (ApplicationDbContext db) => {
            return await db.Students.ToListAsync();
        })
        .WithName("GetAllStudents");

        group.MapGet("/{id}", async Task<Results<Ok<Student>, NotFound>> (int studentid, ApplicationDbContext db) => {
            return await db.Students.AsNoTracking()
                .FirstOrDefaultAsync(model => model.StudentId == studentid)
                is Student model
                    ? TypedResults.Ok(model)
                    : TypedResults.NotFound();
        })
        .WithName("GetStudentById");

        group.MapPut("/{id}", async Task<Results<Ok, NotFound>> (int studentid, Student student, ApplicationDbContext db) => {
            var affected = await db.Students
                .Where(model => model.StudentId == studentid)
                .ExecuteUpdateAsync(setters => setters
                .SetProperty(m => m.StudentId, student.StudentId)
                .SetProperty(m => m.LastName, student.LastName)
                .SetProperty(m => m.FirstName, student.FirstName)
                .SetProperty(m => m.School, student.School)
                .SetProperty(m => m.Gender, student.Gender)
                .SetProperty(m => m.DateOfBirth, student.DateOfBirth)
        );

            return affected == 1 ? TypedResults.Ok() : TypedResults.NotFound();
        })
        .WithName("UpdateStudent");

        group.MapPost("/", async (Student student, ApplicationDbContext db) => {
            db.Students.Add(student);
            await db.SaveChangesAsync();
            return TypedResults.Created($"/api/Student/{student.StudentId}",student);
        })
        .WithName("CreateStudent");

        group.MapDelete("/{id}", async Task<Results<Ok, NotFound>> (int studentid, ApplicationDbContext db) => {
            var affected = await db.Students
                .Where(model => model.StudentId == studentid)
                .ExecuteDeleteAsync();

            return affected == 1 ? TypedResults.Ok() : TypedResults.NotFound();
        })
        .WithName("DeleteStudent");
    }
}

Note the following mapping code in your Program.cs file:

app.MapStudentEndpoints();

You can start the WebAPI app and view all students at endpoint: /api/student.

OPTIONAL: If you want migrations to be applied automatically, add the following code to Program.cs right before the last “app.Run()” statement

using (var scope = app.Services.CreateScope()) {
    var services = scope.ServiceProvider;

    var context = services.GetRequiredService<ApplicationDbContext>();    
    context.Database.Migrate();
}

Adding Swagger Support

It is very easy to add Swagger support to our application so that we can test the various endpoints that our WebAPI application has to offer. 

Add the following code right under app.MapOpenApi():

app.UseSwaggerUI(options =>
{
        options.SwaggerEndpoint("/openapi/v1.json", "My WebAPI");
});

In file Properties/launchSettings.json, set the value of launchBrowser to true in two places:

"launchBrowser": true

Also, add the following property to both the http and https JSON blocks:

"launchUrl": "swagger"

Restart the app by typing dotnet watch in the terminal window. The app will automatically load into your default browser in a Swagger interfact that looks like this:

Go ahead and test all the available student endpoints.

You may encounter the following error when you try any of the endpoints that require an ID parameter - example: /api/Student/{id} endpoint:

This error can easily be resolved by targeting OpenAPI version 3. In Program.cs, replace "builder.Services.AddOpenApi();" with:

builder.Services.AddOpenApi(options => {
    options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0;
});

CORS (Cross-Origin Resource Sharing)

In wwwroot folder, create a file named show.html and add to it this HTML/JavaScript code:

<!DOCTYPE html>
<html>
  <html>
    <head>
      <meta charset="utf-8" />
      <title>Test API</title>
    </head>
    <body>
      <h3>Test API</h3>
      <button id="btnGetData">Get Data</button>
      <pre id="preOutput"></pre>
      <script>
        const url = "PUT-API-URL-HERE";

        var showResponse = function (object) {
          document.querySelector("#preOutput").innerHTML = JSON.stringify(
            object,
            null,
            4
          );
        };

        const button = document.querySelector("#btnGetData");
        button.addEventListener("click", (e) => {
          getData();
        });

        var getData = async function () {
          await fetch(url)
            .then((response) => {
              return response.json();
            })
            .then((data) => {
              showResponse(data);
            });

          return false;
        };
      </script>
    </body>
  </html>
</html>

Replace PUT-API-URL-HERE with the URL that gets all the students (Example: http://localhost:5130/api/students). 

From the file system, double-click on the wwwroot/show.html file. You will see the following page:


When you click on the “Get Data” button, nothing will appear because there is a JavaScript error. To understand where this error is coming from, hit F12 in your browser and check the console. This error will appear:

We need to enable CORS in the WebAPI project. This is done by adding the following code in Program.cs just before “var app = builder.Build();”:
 
// Add Cors
builder.Services.AddCors(o => o.AddPolicy("Policy", builder => {
  builder.AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

Also, in the same Program.cs file, add this code just after “var app = builder.Build();”: 

app.UseCors("Policy");

Save your code then make a new request for data from show.html. This time you should be successful:


The application should work as expected.

Congrats for coming this far.