CRUD w/ Blazor in .NET 8 🔥 All Render Modes (SSR, Server, Wasm, Auto), Entity Framework & SQL Server

4 min read 5 months ago
Published on Aug 02, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial provides a comprehensive guide to building a CRUD application using Blazor in .NET 8. It covers various rendering modes, Entity Framework integration with SQL Server, and step-by-step instructions to implement Create, Read, Update, and Delete functionalities. This guide is perfect for developers looking to leverage the capabilities of Blazor and .NET 8 for modern web applications.

Chapter 1: New Templates and Render Modes Explained

  1. Creating a New Project

    • Open Visual Studio 2022 (Preview Edition).
    • Select Blazor Web App as the project template.
    • Name the project (e.g., BlazerCR.NET8).
    • Choose Authentication Type (default is fine).
    • Configure HTTPS during setup.
  2. Understanding Render Modes

    • None: Static server-side rendering (SSR) without interactivity.
    • Server: Interactivity with server-side rendering using websockets.
    • WebAssembly: Interactivity using WebAssembly, allowing offline capabilities.
    • Auto: Combines both server and WebAssembly modes, switching dynamically based on availability.
  3. Sample Pages

    • Include sample pages such as the weather forecast and counter for testing.

Chapter 2: Preparations for Entity Framework and SQL Server

  1. Setting Up Entities

    • Create a folder named Entities and add a class for the Game entity:
      public class Game
      {
          public int ID { get; set; }
          [Required]
          public string Name { get; set; }
      }
      
  2. Creating Data Context

    • Create a Data folder and add a new class named DataContext:
      public class DataContext : DbContext
      {
          public DataContext(DbContextOptions<DataContext> options) : base(options) { }
          public DbSet<Game> Games { get; set; }
      }
      
  3. Configuring Connection String

    • Set up a connection string in appsettings.json for SQL Server:
      "ConnectionStrings": {
          "DefaultConnection": "Server=localhost;Database=VideoGameDB;Trusted_Connection=True;"
      }
      
  4. Registering Services

    • In Program.cs, add the DataContext and configure it to use SQL Server:
      builder.Services.AddDbContext<DataContext>(options =>
          options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
      
  5. Installing Entity Framework Packages

    • Use NuGet to install Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Design.

Chapter 3: Creating a Service for CRUD Operations

  1. Creating Services Directory

    • Inside the project, create a Services folder and an interface IGameService:
      public interface IGameService
      {
          Task<List<Game>> GetAllGamesAsync();
          Task<Game> AddGameAsync(Game game);
          // Add methods for Update and Delete
      }
      
  2. Implementing GameService

    • Create a class GameService that implements IGameService:
      public class GameService : IGameService
      {
          private readonly DataContext _context;
          public GameService(DataContext context) { _context = context; }
      
          public async Task<List<Game>> GetAllGamesAsync() => await _context.Games.ToListAsync();
      
          public async Task<Game> AddGameAsync(Game game)
          {
              _context.Games.Add(game);
              await _context.SaveChangesAsync();
              return game;
          }
      }
      
  3. Dependency Injection

    • Register the service in Program.cs:
      builder.Services.AddScoped<IGameService, GameService>();
      

Chapter 4: Add Page to Display All Games

  1. Creating Game List Component

    • Create a new Razor component named GameList.razor:
      @page "/games"
      @inject IGameService GameService
      
      @code {
          private List<Game> games;
      
          protected override async Task OnInitializedAsync()
          {
              games = await GameService.GetAllGamesAsync();
          }
      }
      
      <h3>Game List</h3>
      <ul>
          @foreach (var game in games)
          {
              <li>@game.Name</li>
          }
      </ul>
      
  2. Adding Navigation

    • In the navigation menu, add a link to the games page.

Chapter 5: Adding Interactivity with Create/POST Preparations

  1. Create/Edit Game Component

    • Create a new Razor component named EditGame.razor:
      @page "/edit-game/{id:int?}"
      @inject IGameService GameService
      @code {
          [Parameter] public int? ID { get; set; }
          private Game game = new Game();
      
          protected override async Task OnParametersSetAsync()
          {
              if (ID.HasValue)
              {
                  game = await GameService.GetGameByIdAsync(ID.Value);
              }
          }
      
          private async Task HandleSubmit()
          {
              if (ID.HasValue)
              {
                  await GameService.UpdateGameAsync(game);
              }
              else
              {
                  await GameService.AddGameAsync(game);
              }
          }
      }
      
  2. Adding Create Button

    • In GameList.razor, add a button to navigate to the EditGame page:
      <button @onclick="() => NavigationManager.NavigateTo("/edit-game")">Create Game</button>
      

Chapter 6: Implementing Update and Delete Functionality

  1. Update Method in Service

    • Add the UpdateGameAsync method in IGameService and implement it in GameService.
  2. Delete Method in Service

    • Implement the DeleteGameAsync method in IGameService and GameService.
  3. Creating Delete Button

    • In GameList.razor, add delete functionality:
      <button @onclick="() => GameService.DeleteGameAsync(game.ID)">Delete</button>
      
  4. Updating Game Functionality

    • Modify EditGame.razor to handle updates and ensure proper feedback after form submissions.

Conclusion

In this tutorial, we have successfully built a CRUD application using Blazor in .NET 8. We explored different rendering modes, set up Entity Framework with SQL Server, and implemented basic CRUD operations. As a next step, consider enhancing the user experience by adding validation, detailed error handling, and possibly integrating local storage for offline capabilities. Continue experimenting with Blazor's features to unlock its full potential for your web applications.