Database Handling

By Syncfusion®, Inc. · Last updated

Databases in Blazor with EF Core: ORM basics, SQLite setup, connection strings and migrations, entity models, DbContext and DbSet, AddDbContextFactory, a data access service with CRUD and SaveChanges, and showing and changing records from components.

What you will learn

  • Explain what an ORM is and what EF Core does
  • Set up EF Core with SQLite, a connection string and migrations
  • Write an entity model, a DbContext and register it
  • Build a CRUD data service and use it from components

Database Integration Overview

  • A database is a program that stores data safely, so it is still there after the app stops. Think of it as Ravi's big order book.
  • So far, the lessons kept data in a C# List. That list is lost when the app restarts.
  • Database integration means your Blazor app reads and writes its data in a real database.
  • Data in a database lives in tables. A table is like a sheet: each row is one record (one tea), and each column is one value (Name, Price).

Real-World Example:

  • Ravi's tea list and prices change every week.
  • He wants to add, edit and remove teas in his app, and keep them even when the server restarts.
  • So the app stores the teas in a database table called Teas.

A database table called Teas with three columns, Id, Name and Price, and three rows: 1 Masala Tea 20, 2 Ginger Tea 25, 3 Lemon Tea 15. Labels point at one row (one record) and one column (one value).

Table: Teas

Id Name Price

1Masala Tea20 2Ginger Tea25 3Lemon Tea15 one row → (one tea) ← one column

A table has rows (records) and columns (values).

Entity Framework Core (EF Core)

ORM Basics

  • A database speaks its own language, SQL, like SELECT * FROM Teas. Your app speaks C#.
  • An ORM (Object-Relational Mapper) is a translator between the two.
  • It maps (links) a C# class to a table, and each object to one row. You work with C# objects, and the ORM writes the SQL for you.

Animation: a C# object Tea with Name Masala Tea and Price 20 on the left. A dot carries it through a translator box called ORM, which turns it into an SQL line INSERT INTO Teas, and the row appears in the table on the right.

C# object new Tea { Name = "Masala Tea", Price = 20 }

ORM (EF Core)

Table: Teas 4 | Masala Tea | 20 INSERT INTO Teas (Name, Price) VALUES ('Masala Tea', 20)

The ORM turns C# objects into SQL, and table rows back into C# objects.

EF Core Overview

  • Entity Framework Core (EF Core) is Microsoft's ORM for .NET. It is the usual way to use a database in a Blazor app.
  • It works with many databases: SQLite (a small database in one file, great for learning), SQL Server, PostgreSQL and more.
  • You write C# like db.Teas.Where(t => t.Price < 25), and EF Core sends the SQL and gives you Tea objects back.
  • EF Core runs on the server. A WebAssembly component cannot reach the database directly. It calls a Web API on the server instead.

Database Configuration

These are the steps to connect the app to a database. This lesson uses SQLite, because it needs no extra setup.

Six steps in a row: 1 add packages, 2 entity model, 3 DbContext, 4 connection string, 5 register in Program.cs, 6 create the database. A dot moves from step to step.

1. Addpackages 2. Entitymodel 3. DbContext 4. Connectionstring 5. Registerin Program.cs 6. Create thedatabase

The six setup steps. Each one is explained below.

EF Core Setup

  • EF Core comes as NuGet packages: ready-made libraries you add to the project.
  • Add the SQLite provider and the design tools. Also install the dotnet ef command once on your computer.

Click Next to see each command.

Connection Strings

  • A connection string is the address of the database, plus how to log in.
  • Keep it in appsettings.json under ConnectionStrings, not in your C# code.
  • For SQLite, it is just the file name: Data Source=teashop.db.

A real server's connection string often has a password. Never put it in a public Git repository. On your computer, use User Secrets (dotnet user-secrets). On the server, use environment variables.

Database Creation

  • The database and its tables are created with a migration: a small C# file that EF Core writes, describing how to build or change the tables.
  • dotnet ef migrations add InitialCreate writes the first migration from your models.
  • dotnet ef database update runs it, so teashop.db and the Teas table are created.
  • After you change a model, add a new migration and run database update again.

Click Next to see each command.

Models and DbContext

Entity Models

  • An entity model (entity) is a C# class that EF Core maps to a table. Tea becomes the Teas table.
  • Each property becomes a column. A property called Id becomes the primary key: the unique number of each row.

In the below example, Models/Tea.cs is the entity. The page makes Tea objects, the same objects EF Core gives you from the database.

DbContext and DbSet

  • DbContext is EF Core's main class. It is your session with the database: it reads rows, keeps track of changes and saves them.
  • Make your own class that inherits DbContext, like TeaShopContext.
  • Inside it, a DbSet<Tea> property stands for one table. db.Teas is the Teas table.

TeaShopContext box containing a DbSet called Teas. An arrow links the DbSet to the Teas table in the teashop.db database file.

TeaShopContext

DbSet<Tea> Teas

teashop.db

Table: Teas

maps to

The DbContext holds one DbSet for each table.

Registering DbContext

  • Register the context in Program.cs, so the DI container can make it (see Dependency Injection).
  • In Blazor, use AddDbContextFactory. A factory is an object that makes a fresh DbContext each time you need one. This suits Blazor, where a page stays open for a long time.
  • UseSqlite picks the database, and GetConnectionString("TeaShop") reads the connection string from appsettings.json.

In a Blazor Server app, one DbContext must not be shared by many actions at once. Making a short-lived one from the factory for each job avoids that problem.

Creating Data Access Service

  • Following Services, the database code goes into a service, not into the components.
  • TeaService gets the IDbContextFactory through its constructor, and has one method per CRUD job.
  • Each method makes a short-lived context with await using var db = await factory.CreateDbContextAsync();.
  • Async methods (ending in Async) wait for the database without freezing the app.

Creating Records

  • db.Teas.Add(tea) marks a new tea to be inserted. Nothing is saved yet.

Reading Records

  • db.Teas.ToListAsync() reads all rows. Add LINQ methods (C# query words) to filter and sort: Where, OrderBy, FirstOrDefault.
  • EF Core turns the LINQ into SQL, so only the rows you need come back.

The same LINQ also works on a normal list. In the below example, Where and OrderBy pick the teas under ₹25, cheapest first. With EF Core, this exact code runs as SQL in the database.

Updating Records

  • Change the properties, then save. db.Teas.Update(tea) marks every column of the row as changed.

Deleting Records

  • Find the row, mark it with db.Teas.Remove(tea), then save.

Saving Changes

  • Add, Update and Remove only mark changes in the DbContext. The database does not change yet.
  • await db.SaveChangesAsync() sends all marked changes to the database together. If one fails, none are saved.
  • Forget SaveChangesAsync, and nothing is stored.

Animation: three changes, Add Lemon Tea, Update Masala Tea price and Remove Ginger Tea, pile up in a tray inside DbContext. Then SaveChangesAsync sends the whole tray to the database at once, and the tray empties.

DbContext: marked changes

Add: Lemon Tea

Update: Masala Tea → ₹22

Remove: Ginger Tea

Database 3 changes saved

SaveChangesAsync()

Changes wait in the DbContext. SaveChangesAsync sends them all at once.

Register the service in Program.cs, next to the context:

Working with Databases in Blazor

  • Components never touch the DbContext. They inject ITeaService and call its methods, as in Services.
  • The code boxes cannot run a database. So below, MemoryTeaService stands in for TeaService: it has the same methods, waits half a second like a database, and keeps the teas in memory. AppServices.cs stands in for Program.cs.

Animation of the layers: TeaList.razor calls ITeaService, TeaService uses DbContext, DbContext talks to the database. A dot travels down the layers and comes back with the list of teas.

TeaList.razor TeaService DbContext Database

shows teas CRUD methods LINQ → SQL stores rows

The component talks to the service. Only the service talks to EF Core.

MemoryTeaService and AppServices exist only so the code boxes can run. In your app, use the EF Core TeaService and register it in Program.cs.

Displaying Database Records

  • Load the records in OnInitializedAsync (see Component Lifecycle).
  • Show "Loading..." while the list is still null, because the database takes a moment.

In the below example, TeaList.razor loads the teas from ITeaService and shows them in a table.

Performing CRUD Operations from Components

  • Each button calls one service method, then reloads the list, so the page shows the database as it is now.
  • Reuse what you learned in Forms & Events for the form.

In the below example, you can add a tea, raise a price by ₹5 and delete a tea. Every change goes through ITeaService.

To edit a record, load it into a form, let the user change it, and save it with UpdateAsync. In the below example, pick a tea, change its price and click Save.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
Calling Add or Remove without SaveChangesAsyncAdd saves the rowCall await db.SaveChangesAsync()Nothing is stored
One DbContext shared for the whole time a page is openOne context is enoughUse AddDbContextFactory and a short-lived context per jobErrors when two actions run at once
A password in the connection string in Gitappsettings.json is privateUse User Secrets or environment variablesAnyone can read the password
Using EF Core in a WebAssembly componentThe browser can reach the databaseCall a Web API on the serverThe component cannot reach the database
db.Teas.ToList() without await ... ToListAsync()Sync is fineUse the Async methods with awaitThe app freezes while it waits
Changing a model and not adding a migrationThe table updates by itselfRun dotnet ef migrations add and database updateErrors about missing columns

Check Yourself

Exercises

What to Remember

  • A database keeps data in tables of rows and columns, safe after the app stops.
  • EF Core is an ORM: it maps C# classes to tables and writes the SQL for you. It runs on the server.
  • Setup: add the packages, write the entity model and DbContext, put the connection string in appsettings.json, register with AddDbContextFactory, then create the database with dotnet ef migrations add and dotnet ef database update.
  • DbContext is a session with the database. Each DbSet<T> is one table.
  • CRUD: Add, LINQ with ToListAsync, Update, Remove. Nothing is stored until SaveChangesAsync.
  • Put database code in a service. Components inject it, load data in OnInitializedAsync, show "Loading..." and reload after each change.

Next: API Integration