Microsoft Blazor – Because It’s So Darn Easy!

Author Note: I am a developer consultant who creates new software solutions and maintains existing solutions for my clients. I have been doing this for over 20 years. I primarily work with Microsoft technologies.

This article will demonstrate how easy it is to create a Blazor website that displays data from a database with full CRUD interactions. It will include the process of creating the project, understanding the choices for the render modes, Using Entity Framework scaffolding tools, web scaffolding, and the awesome QuickGrid with full CRUD interactions and links to other pages displaying related data. We wrap up with a brief overview of some 3rd party Blazor tools. I will be using Visual Studio but much of this could be done with VS Code and Command Line Interface (CLI) as well.

Install the EF Core Power Tools

The first thing we should do is install a helpful Entity Framework (EF) Visual Studio extension called the EF Core Power Tools. This open-source extension was created and is continuously supported by Erik Ejlskov Jensen (ErikEJ). You can add this extension to different versions of Visual Studio.

Start Visual Studio 2022+ and then click “Continue without code.”

Click “Extensions | Manage Extensions…”
On the Browse tab, search for EF Core Power to find two related extensions.

The EF Core Power Pack includes additional database providers for SQLite and PostgreSQL and a few other useful extensions. Importantly, it also includes the EF Core Power Tools.

There are other Entity Framework extensions available for different versions of the .NET Framework and .NET (Core) listed here: https://learn.microsoft.com/en-us/ef/core/extensions/

The EF Core Power Tools include several useful tools developers can use to create Plain Old CLR Objects (POCOs), DBContext objects, Text Template Transformation Toolkit (known as T4) code generators, DGML model diagrams are useful for scaffolding from an existing database. Definitely worth checking out!

Install the EF Core Power Pack extension (installs both for you) into Visual Studio 2022 (Community, Professional, or Enterprise).

Create a New Blazor Project

STEP 1: Click the New Project toolbar button to create a new project.

STEP 2: Enter blazor into the search box and choose the first project template (Blazor Web App) as shown.

This one super template will allow you to create different Blazor apps:
– Server-Side Rendering (SSR) app
– Blazor Server App
– Blazor WebAssembly App
– Blazor Mixed (Auto) web application

Note that the project template immediately below it (Blazor WebAssembly Standalone App) is for creating a Single Page Application (SPA) or a Progressive Web Application (PWA) that can be automatically installed as a desktop application. This template does not include a server-side project.

NOTE: Beware of the other Blazor project templates that appear such as Blazor Server App. They are leftover templates for earlier versions of .NET such as .NET 6 or the currently unsupported .NET 7 version.

STEP 3: Give your project a meaningful name and click Next.

STEP 4: Choose the version of .NET you are using. Since I am using the Preview version of Visual Studio 2022 and I have the latest (at the time of writing) version of .NET 9 SDK installed, I will choose it.

STEP 5: We will leave the Authentication type at None.

Note that if you choose Individual Accounts, it will add several more files and components with an EF database connection to store account information in a LocalDB database.

STEP 6: Leave the Configure for HTTPS option checked.

STEP 7: Set the Interactive render mode to Server.

The Interactive render mode section is important. Depending on the mode you select, it will add some special commands to the Program.cs file in two different areas. These settings can be changed afterwards so it’s not the end of the world if you decide to change the mode you want to run with. Alternately, just create a new project!

  • None: Content is rendered on the web server and then the content is sent to the web browser. This is pure Static Server-Side Rendering (SSR). There is no interactive library being used. This render mode is even less interactive than classic ASP.NET web forms – LOL! If you want a button click event to call code on the server, you need to write the code to do that yourself! Consider using VanillaJS, htmx, jQuery, etc.
  • Server: This render mode includes the powerful SignalR library to support interactive SSR. Beneath the covers, SignalR uses the WebSocket protocol to communicate with the server. It can also fall back to other transport methods such as Server-Sent Events (SSE), Long Polling, and Forever Frame if WebSocket is not supported by the network or web browser.
  • In this mode, the server tracks the DOM and all the events. The web application maintains a solid connection with the server and either client/server can send updates to the other side.

  • WebAssembly: This render mode uses interactive client-side rendering (CSR) with a special lightweight version of .NET Mono downloaded to the user’s web browser. It runs the Intermediate Language (IL) code using WebAssembly (wasm) – the fourth major API supported by all of today’s web browsers that can run compiled code. Think of the WebAssembly model as Microsoft’s answer to the popularity of React, Angular, and Vue SPAs. However, developers can write the code in C# instead of JavaScript (JS) or TypeScript (TS). A bummer when choosing project type is the initial load cost in time for the first page. Not only is the web browser downloading the web page but it is also downloading the wasm to execute the .NET code on the client side.
  • Auto (Server and WebAssembly): New with .NET 8, this model combines the Server and WebAssembly rendering modes. It initially begins as a Server SignalR connection, so the page appears responsive as a regular Blazor server app. Meanwhile, in the background after the initial page is loaded, it continues to download the wasm and app until it is fully downloaded. It then acts as an interactive CSR app.
  • STEP 8: For the Interactive location, we will leave it at Global. The alternative is to set the interactive level at the component or page level. You can still override the render mode at either of these two levels. It’s just nice to set the default globally for the entire app in Program.cs.

    STEP 9: I like to include the starter sample pages by leaving the Include sample pages checkbox as checked. It creates the needed folder structure for this example. With more experience these can be dropped.

    STEP 10: For Do not use top-level statements, I like to check that option. I admit I am a bit “old school”. I like to see both the container Program class with the main() method in the cs file. However, if you prefer the new alternative for defining the entry point, you may certainly uncheck this option. Maybe I’ll eventually get used to it and start using top level statements for my main() methods in my C# projects.

    STEP 11: Click the Create button to create the website.

    Install the EF Libraries into the Project

    STEP 1: We need to add two NuGet packages to our new project. Right-click the project (not the solution!) and click Manage NuGet Packages…

    STEP 2: Click the Browse tab first! Then install the two packages, Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer.

    NOTE: I’ve checked the Include Prerelease checkbox so I can install the .NET 9 version of these NuGet packages. Se sure you match the packages to the version of .NET you selected when you created the project.

    These two libraries will give us access to a database using Entity Framework and SQL Server.
    Another package titled Microsoft.EntityFrameworkCore.Tools will give you the option to reverse engineer a database via CLI using the Package Manager Console (PMC). Instead, we will use the EF Core Power Tools here. It has many more options.

    STEP 3: For each package, Click Install, Apply, and I Accept to install the latest versions of the packages.
    When I installed one of the packages, a warning appeared in Visual Studio about some dependent packages having vulnerabilities – specifically Identity packages. Nice. ☹

     

    Scaffold EF Objects

    Right click the project and click EF Core Power Tools | Reverse Engineer.

    Add a connection to the database you want to scaffold and select it. Incidentally, I am using a free sample database from Microsoft called WideWorldImporters. Be sure to choose the correct version of EF Core that you installed earlier and click OK.

    Next, you select the database objects you wish to scaffold. Because I am using SQL Server, I can choose from tables, views, and stored procedures.

    Notice that I can choose a schema, a table, or even specific columns. I appreciate the search feature at the top (pictured) for wrangling larger databases.

    Be careful not to choose table columns that have complex data types. For example, do not choose spatial data types (geography, geometry), LOB data types (text/ntext, image), UDTs, and computed columns. They are too complex to scaffold.

    I’m choosing the Cities table. I’m using SQL Server Management Studio (SSMS) to help me select the columns I want. Notice that I am not including Location because it is a geography column.

    The next dialog gives me several options for scaffolding the code. By default, the files will be put in a folder called Models. Cool! The tool will even install the EF Core NuGet packages for me if I forgot to do that in a previous step. I’ll just click OK.

    After a little churning, the Models folder appears with a couple of important classes – the almight DbContext class and the table I reverse-engineered.

     

    Add Connection Information to Program.cs and appsettings.json

    We need to register our Context Factory service with a connection string used for scaffolding the Razor pages with the QuickGrid component.

    In Program.cs we should add it right after we create the builder variable (mind the code wrap):
    // Provider for the WideWorldImporters database

    builder.Services.AddDbContextFactory<WideWorldImportersContext>(options =>    options.UseSqlServer(builder.Configuration.GetConnectionString(“WideWorldImporters”)));

     

    As well, expand appsettings.json and open appsettings.Development.json.

    Add our connection string above the Logging section (again, mind the code wrap):
      “ConnectionStrings”: {

        “WideWorldImporters”: “Data Source=.;Initial Catalog=WideWorldImporters;Integrated Security=True;Trust Server Certificate=True”

      },

     

    Scaffold the QuickGrid Pages

    New with .NET 8+, we can scaffold Razor pages with the new Blazor QuickGrid component for full CRUD editing! Right-click the Pages folder and click Add and then New Scaffolded Item…

    On the left side, choose Blazor. On the right side, choose Razor Components using Entity Framework (CRUD).
    NOTE: Be careful here. Although we are creating a bunch of Razor pages, we don’t not want to confuse them with the other scaffolding choices here! Some other choices are called Razor Pages but we don’t want to use them. As a best practice, we should use the scaffolding templates with the Blazor icons. When you select the correct scaffolding template, click Add.

    The last dialog has us choose our model and context classes. Note that if you didn’t want full CRUD, you can change it to a specific operation.

    Click Add and wait a bit for the code generation and NuGet Package registration to take place.
    If everything was created successfully, you should now have a set of new Razor pages in a new <Model>Pages folder under the main /Pages folder, cleverly named after your selected model class.

    Open the Index page and read the page name at the top. You will use this navigation shortly.

     

    Test the Website

    Run the application and open the Counter page.

    Change the URL to use name at the top of your Index page.

    Try experimenting with the Create, Edit, Details, and Delete methods. If you make changes to the data, they are committed back to the database.

    If you take a look at the web pages, you can see how easy they are to modify. Pagination and sorting can easily be added to the QuickGrid. If you study the Create and Edit pages, you will see they are using another new Blazor component from Microsoft – the EditForm component! It supports validation for data entered into the fields.

     

    Blazor Component Libraries

    If you are considering using a library to help dress up your website, it may make some things easier, depending on the complexity and support your website needs. Be aware that adding a UI library may make it more difficult to internationalize your website or to include accessibility tools. It can depend on the complexity of the web pages requiring interaction such as menus or forms with their controls.

    Here are some free libraries created specifically for Microsoft Blazor. I’ll be honest, I mostly hear from Blazor devs using Radzen or MudBlazor and their arguments why they prefer that library over the other. However, the others are worth looking at. By the way – I included some commercial options on the last bullet.

    I hope this has been helpful for you!

    • Radzen Blazor Components
    • MudBlazor
    • Blazored
    • Blazorise
    • MatBlazor
    • Microsoft Fluent UI Blazor Components
    • Blazored
    • Ant Design Blazor
    • Havit Blazor
    • Commercial options include the usual suspects such as Telerik, Syncfusion, DevExpress, Infragistics, ComponentOne, SmartUI, and more.

    About Intertech

    Intertech is a Software Development Consulting Firm that provides single and multiple turnkey software development teams, available on your schedule and configured to achieve success as defined by your requirements independently or in co-development with your team. Intertech teams combine proven full-stack, DevOps, Agile-experienced lead consultants with Delivery Management, User Experience, Software Development, and QA experts in Business Process Automation (BPA), Microservices, Client- and Server-Side Web Frameworks of multiple technologies, Custom Portal and Dashboard development, Cloud Integration and Migration (Azure and AWS), and so much more. Each Intertech employee leads with the soft skills necessary to explain complex concepts to stakeholders and team members alike and makes your business more efficient, your data more valuable, and your team better. In addition, Intertech is a trusted partner of more than 4000 satisfied customers and has a 99.70% “would recommend” rating.