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 youTeaobjects 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 efcommand 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.jsonunderConnectionStrings, 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 InitialCreatewrites the first migration from your models.dotnet ef database updateruns it, soteashop.dband theTeastable are created.- After you change a model, add a new migration and run
database updateagain.
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.
Teabecomes theTeastable. - Each property becomes a column. A property called
Idbecomes 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
DbContextis 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, likeTeaShopContext. - Inside it, a
DbSet<Tea>property stands for one table.db.Teasis theTeastable.
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 freshDbContexteach time you need one. This suits Blazor, where a page stays open for a long time. UseSqlitepicks the database, andGetConnectionString("TeaShop")reads the connection string fromappsettings.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.
TeaServicegets theIDbContextFactorythrough 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,UpdateandRemoveonly mark changes in theDbContext. 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 injectITeaServiceand call its methods, as in Services. - The code boxes cannot run a database. So below,
MemoryTeaServicestands in forTeaService: it has the same methods, waits half a second like a database, and keeps the teas in memory.AppServices.csstands in forProgram.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
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
Calling Add or Remove without SaveChangesAsync | Add saves the row | Call await db.SaveChangesAsync() | Nothing is stored |
One DbContext shared for the whole time a page is open | One context is enough | Use AddDbContextFactory and a short-lived context per job | Errors when two actions run at once |
| A password in the connection string in Git | appsettings.json is private | Use User Secrets or environment variables | Anyone can read the password |
| Using EF Core in a WebAssembly component | The browser can reach the database | Call a Web API on the server | The component cannot reach the database |
db.Teas.ToList() without await ... ToListAsync() | Sync is fine | Use the Async methods with await | The app freezes while it waits |
| Changing a model and not adding a migration | The table updates by itself | Run dotnet ef migrations add and database update | Errors 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 inappsettings.json, register withAddDbContextFactory, then create the database withdotnet ef migrations addanddotnet ef database update. DbContextis a session with the database. EachDbSet<T>is one table.- CRUD:
Add, LINQ withToListAsync,Update,Remove. Nothing is stored untilSaveChangesAsync. - Put database code in a service. Components inject it, load data in
OnInitializedAsync, show "Loading..." and reload after each change.
Next: API Integration