CRUD w/ Blazor in .NET 8 🔥 All Render Modes (SSR, Server, Wasm, Auto), Entity Framework & SQL Server
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
-
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.
-
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.
-
Sample Pages
- Include sample pages such as the weather forecast and counter for testing.
Chapter 2: Preparations for Entity Framework and SQL Server
-
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; } }
- Create a folder named
-
Creating Data Context
- Create a
Data
folder and add a new class namedDataContext
:public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Game> Games { get; set; } }
- Create a
-
Configuring Connection String
- Set up a connection string in
appsettings.json
for SQL Server:"ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=VideoGameDB;Trusted_Connection=True;" }
- Set up a connection string in
-
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")));
- In
-
Installing Entity Framework Packages
- Use NuGet to install
Microsoft.EntityFrameworkCore.SqlServer
andMicrosoft.EntityFrameworkCore.Design
.
- Use NuGet to install
Chapter 3: Creating a Service for CRUD Operations
-
Creating Services Directory
- Inside the project, create a
Services
folder and an interfaceIGameService
:public interface IGameService { Task<List<Game>> GetAllGamesAsync(); Task<Game> AddGameAsync(Game game); // Add methods for Update and Delete }
- Inside the project, create a
-
Implementing GameService
- Create a class
GameService
that implementsIGameService
: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; } }
- Create a class
-
Dependency Injection
- Register the service in
Program.cs
:builder.Services.AddScoped<IGameService, GameService>();
- Register the service in
Chapter 4: Add Page to Display All Games
-
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>
- Create a new Razor component named
-
Adding Navigation
- In the navigation menu, add a link to the games page.
Chapter 5: Adding Interactivity with Create/POST Preparations
-
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); } } }
- Create a new Razor component named
-
Adding Create Button
- In
GameList.razor
, add a button to navigate to theEditGame
page:<button @onclick="() => NavigationManager.NavigateTo("/edit-game")">Create Game</button>
- In
Chapter 6: Implementing Update and Delete Functionality
-
Update Method in Service
- Add the
UpdateGameAsync
method inIGameService
and implement it inGameService
.
- Add the
-
Delete Method in Service
- Implement the
DeleteGameAsync
method inIGameService
andGameService
.
- Implement the
-
Creating Delete Button
- In
GameList.razor
, add delete functionality:<button @onclick="() => GameService.DeleteGameAsync(game.ID)">Delete</button>
- In
-
Updating Game Functionality
- Modify
EditGame.razor
to handle updates and ensure proper feedback after form submissions.
- Modify
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.