# Database Handling

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Data Access
Source: https://www.devtutorials.ai/learn/blazor/data-access/database-handling

> 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.

## 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`.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-db-table">
  <title id="fig-db-table">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).</title>
  <defs><marker id="fig-db-table-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="120" y="30" width="400" height="150" rx="10" />
  <text className="t m" x="320" y="22" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Table: Teas</text>
  <rect className="pur" x="120" y="30" width="400" height="34" rx="10" />
  <text className="t m" x="160" y="52" style={{ fontSize: 12, fontWeight: 700 }}>Id</text>
  <text className="t m" x="240" y="52" style={{ fontSize: 12, fontWeight: 700 }}>Name</text>
  <text className="t m" x="430" y="52" style={{ fontSize: 12, fontWeight: 700 }}>Price</text>
  <rect className="org" x="124" y="70" width="392" height="30" rx="5" />
  <text className="t m" x="160" y="90" style={{ fontSize: 12 }}>1</text><text className="t m" x="240" y="90" style={{ fontSize: 12 }}>Masala Tea</text><text className="t m" x="430" y="90" style={{ fontSize: 12 }}>20</text>
  <text className="t m" x="160" y="125" style={{ fontSize: 12 }}>2</text><text className="t m" x="240" y="125" style={{ fontSize: 12 }}>Ginger Tea</text><text className="t m" x="430" y="125" style={{ fontSize: 12 }}>25</text>
  <text className="t m" x="160" y="160" style={{ fontSize: 12 }}>3</text><text className="t m" x="240" y="160" style={{ fontSize: 12 }}>Lemon Tea</text><text className="t m" x="430" y="160" style={{ fontSize: 12 }}>15</text>
  <text className="t" x="20" y="90" style={{ fontSize: 11 }}>one row →</text>
  <text className="t" x="20" y="104" style={{ fontSize: 11 }}>(one tea)</text>
  <text className="t" x="540" y="125" style={{ fontSize: 11 }}>← one</text>
  <text className="t" x="540" y="139" style={{ fontSize: 11 }}>column</text>
</svg>
<figcaption>A table has rows (records) and columns (values).</figcaption>
</figure>

## 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 175" role="img" aria-labelledby="fig-db-orm">
  <title id="fig-db-orm">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.</title>
  <defs><marker id="fig-db-orm-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="40" width="170" height="100" rx="10" />
  <text className="t m" x="105" y="64" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>C# object</text>
  <text className="t m" x="105" y="92" textAnchor="middle" style={{ fontSize: 11 }}>new Tea &#123;</text>
  <text className="t m" x="105" y="108" textAnchor="middle" style={{ fontSize: 11 }}>Name = "Masala Tea",</text>
  <text className="t m" x="105" y="124" textAnchor="middle" style={{ fontSize: 11 }}>Price = 20 &#125;</text>
  <rect className="org" x="250" y="60" width="140" height="60" rx="10" />
  <text className="t m" x="320" y="86" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>ORM</text>
  <text className="t" x="320" y="106" textAnchor="middle" style={{ fontSize: 10 }}>(EF Core)</text>
  <rect className="box" x="450" y="40" width="170" height="100" rx="10" />
  <text className="t m" x="535" y="64" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Table: Teas</text>
  <text className="t m" x="535" y="100" textAnchor="middle" style={{ fontSize: 11 }}>4 | Masala Tea | 20<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.7;0.75;1" dur="5s" repeatCount="indefinite" /></text>
  <text className="t m" x="320" y="160" textAnchor="middle" style={{ fontSize: 11 }}>INSERT INTO Teas (Name, Price) VALUES ('Masala Tea', 20)<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.4;0.45;0.8;0.9" dur="5s" repeatCount="indefinite" /></text>
  <path className="line" d="M190 90 H246" markerEnd="url(#fig-db-orm-a)" />
  <path className="line" d="M390 90 H446" markerEnd="url(#fig-db-orm-a)" />
  <circle r="7" cy="90" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="190;320;320;450;450" keyTimes="0;0.3;0.45;0.7;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The ORM turns C# objects into SQL, and table rows back into C# objects.</figcaption>
</figure>

### 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 130" role="img" aria-labelledby="fig-db-steps">
  <title id="fig-db-steps">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.</title>
  <defs><marker id="fig-db-steps-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="10" y="40" width="95" height="56" rx="8" /><text className="t m" x="57" y="64" textAnchor="middle" style={{ fontSize: 11 }}>1. Add</text><text className="t m" x="57" y="80" textAnchor="middle" style={{ fontSize: 11 }}>packages</text>
  <rect className="box" x="115" y="40" width="95" height="56" rx="8" /><text className="t m" x="162" y="64" textAnchor="middle" style={{ fontSize: 11 }}>2. Entity</text><text className="t m" x="162" y="80" textAnchor="middle" style={{ fontSize: 11 }}>model</text>
  <rect className="box" x="220" y="40" width="95" height="56" rx="8" /><text className="t m" x="267" y="64" textAnchor="middle" style={{ fontSize: 11 }}>3. DbContext</text>
  <rect className="box" x="325" y="40" width="95" height="56" rx="8" /><text className="t m" x="372" y="64" textAnchor="middle" style={{ fontSize: 11 }}>4. Connection</text><text className="t m" x="372" y="80" textAnchor="middle" style={{ fontSize: 11 }}>string</text>
  <rect className="box" x="430" y="40" width="95" height="56" rx="8" /><text className="t m" x="477" y="64" textAnchor="middle" style={{ fontSize: 11 }}>5. Register</text><text className="t m" x="477" y="80" textAnchor="middle" style={{ fontSize: 11 }}>in Program.cs</text>
  <rect className="grn" x="535" y="40" width="95" height="56" rx="8" /><text className="t m" x="582" y="64" textAnchor="middle" style={{ fontSize: 11 }}>6. Create the</text><text className="t m" x="582" y="80" textAnchor="middle" style={{ fontSize: 11 }}>database</text>
  <circle r="7" cy="112" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="57;162;267;372;477;582;582" keyTimes="0;0.15;0.3;0.45;0.6;0.75;1" dur="6s" repeatCount="indefinite" calcMode="discrete" />
  </circle>
</svg>
<figcaption>The six setup steps. Each one is explained below.</figcaption>
</figure>

### 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.

### 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.

## 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.

}

@code {
      // Later, these come from the database
      private List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
      };
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

### 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 170" role="img" aria-labelledby="fig-db-context">
  <title id="fig-db-context">TeaShopContext box containing a DbSet called Teas. An arrow links the DbSet to the Teas table in the teashop.db database file.</title>
  <defs><marker id="fig-db-context-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="30" width="260" height="120" rx="12" />
  <text className="t m" x="150" y="56" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>TeaShopContext</text>
  <rect className="blu" x="50" y="76" width="200" height="50" rx="8" />
  <text className="t m" x="150" y="106" textAnchor="middle" style={{ fontSize: 12 }}>DbSet&lt;Tea&gt; Teas</text>
  <rect className="box" x="390" y="30" width="230" height="120" rx="12" />
  <text className="t m" x="505" y="56" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>teashop.db</text>
  <rect className="org" x="420" y="76" width="170" height="50" rx="8" />
  <text className="t m" x="505" y="106" textAnchor="middle" style={{ fontSize: 12 }}>Table: Teas</text>
  <path className="line" d="M250 101 H416" markerEnd="url(#fig-db-context-a)" />
  <text className="t" x="333" y="92" textAnchor="middle" style={{ fontSize: 11 }}>maps to</text>
</svg>
<figcaption>The DbContext holds one DbSet for each table.</figcaption>
</figure>

### 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`.

      options.UseSqlite(builder.Configuration.GetConnectionString("TeaShop")));

var app = builder.Build();
`}
/>

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.

@foreach (var tea in cheap)
{
      <p>@tea.Name: ₹@tea.Price</p>
}

@code {
      private List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };

      // With EF Core: db.Teas.Where(...).OrderBy(...).ToListAsync()
      private List<Tea> cheap => teas.Where(t => t.Price < 25).OrderBy(t => t.Price).ToList();
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

### 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 190" role="img" aria-labelledby="fig-db-save">
  <title id="fig-db-save">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.</title>
  <defs><marker id="fig-db-save-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="20" width="300" height="150" rx="12" />
  <text className="t m" x="170" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>DbContext: marked changes</text>
  <rect className="grn" x="40" y="58" width="260" height="28" rx="6"><animate attributeName="opacity" values="0;1;1;1;0;0" keyTimes="0;0.1;0.5;0.65;0.7;1" dur="6s" repeatCount="indefinite" /></rect>
  <text className="t m" x="170" y="77" textAnchor="middle" style={{ fontSize: 11 }}>Add: Lemon Tea<animate attributeName="opacity" values="0;1;1;1;0;0" keyTimes="0;0.1;0.5;0.65;0.7;1" dur="6s" repeatCount="indefinite" /></text>
  <rect className="org" x="40" y="92" width="260" height="28" rx="6"><animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0;0.2;0.25;0.65;0.7;1" dur="6s" repeatCount="indefinite" /></rect>
  <text className="t m" x="170" y="111" textAnchor="middle" style={{ fontSize: 11 }}>Update: Masala Tea → ₹22<animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0;0.2;0.25;0.65;0.7;1" dur="6s" repeatCount="indefinite" /></text>
  <rect className="box" x="40" y="126" width="260" height="28" rx="6"><animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0;0.35;0.4;0.65;0.7;1" dur="6s" repeatCount="indefinite" /></rect>
  <text className="t m" x="170" y="145" textAnchor="middle" style={{ fontSize: 11 }}>Remove: Ginger Tea<animate attributeName="opacity" values="0;0;1;1;0;0" keyTimes="0;0.35;0.4;0.65;0.7;1" dur="6s" repeatCount="indefinite" /></text>
  <rect className="box" x="440" y="50" width="180" height="90" rx="12" />
  <text className="t m" x="530" y="90" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Database</text>
  <text className="t" x="530" y="112" textAnchor="middle" style={{ fontSize: 11 }}>3 changes saved<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.7;0.75;1" dur="6s" repeatCount="indefinite" /></text>
  <path className="line" d="M320 95 H436" markerEnd="url(#fig-db-save-a)" />
  <text className="t m" x="378" y="86" textAnchor="middle" style={{ fontSize: 10 }}>SaveChangesAsync()</text>
  <circle r="8" cy="95" style={{ fill: "#7c3aed" }} opacity="0">
    <animate attributeName="cx" values="320;320;436;436" keyTimes="0;0.6;0.7;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="opacity" values="0;0;1;0" keyTimes="0;0.6;0.65;0.72" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Changes wait in the DbContext. SaveChangesAsync sends them all at once.</figcaption>
</figure>

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`.

<figure className="blz-fig">
<svg viewBox="0 0 640 160" role="img" aria-labelledby="fig-db-layers">
  <title id="fig-db-layers">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.</title>
  <defs><marker id="fig-db-layers-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="20" y="60" width="130" height="60" rx="10" /><text className="t m" x="85" y="95" textAnchor="middle" style={{ fontSize: 12 }}>TeaList.razor</text>
  <rect className="pur" x="180" y="60" width="130" height="60" rx="10" /><text className="t m" x="245" y="95" textAnchor="middle" style={{ fontSize: 12 }}>TeaService</text>
  <rect className="org" x="340" y="60" width="130" height="60" rx="10" /><text className="t m" x="405" y="95" textAnchor="middle" style={{ fontSize: 12 }}>DbContext</text>
  <rect className="box" x="500" y="60" width="120" height="60" rx="10" /><text className="t m" x="560" y="95" textAnchor="middle" style={{ fontSize: 12 }}>Database</text>
  <path className="line" d="M150 90 H176" markerEnd="url(#fig-db-layers-a)" /><path className="line" d="M310 90 H336" markerEnd="url(#fig-db-layers-a)" /><path className="line" d="M470 90 H496" markerEnd="url(#fig-db-layers-a)" />
  <text className="t" x="85" y="145" textAnchor="middle" style={{ fontSize: 10 }}>shows teas</text>
  <text className="t" x="245" y="145" textAnchor="middle" style={{ fontSize: 10 }}>CRUD methods</text>
  <text className="t" x="405" y="145" textAnchor="middle" style={{ fontSize: 10 }}>LINQ → SQL</text>
  <text className="t" x="560" y="145" textAnchor="middle" style={{ fontSize: 10 }}>stores rows</text>
  <circle r="7" cy="75" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="85;560;85" dur="4s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The component talks to the service. Only the service talks to EF Core.</figcaption>
</figure>

`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.

}
else
{
      <table>
          <tr><th>Tea</th><th>Price</th></tr>
          @foreach (var tea in teas)
          {
              <tr><td>@tea.Name</td><td>₹@tea.Price</td></tr>
          }
      </table>
}

@code {
      // In your app: @inject ITeaService Teas
      private ITeaService Teas = AppServices.Container.GetRequiredService<ITeaService>();
      private List<Tea>? teas;

      protected override async Task OnInitializedAsync()
      {
          teas = await Teas.GetAllAsync();
      }
}
`,
    "Services/MemoryTeaService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for the EF Core TeaService: same methods, data kept in memory.
public class MemoryTeaService : ITeaService
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public async Task<List<Tea>> GetAllAsync()
      {
          await Task.Delay(500); // pretend to wait for the database
          return teas.OrderBy(t => t.Name).ToList();
      }

      public Task AddAsync(Tea tea)
      {
          tea.Id = nextId++;
          teas.Add(tea);
          return Task.CompletedTask;
      }

      public Task UpdateAsync(Tea tea)
      {
          var old = teas.FirstOrDefault(t => t.Id == tea.Id);
          if (old != null) { old.Name = tea.Name; old.Price = tea.Price; }
          return Task.CompletedTask;
      }

      public Task DeleteAsync(int id)
      {
          teas.RemoveAll(t => t.Id == id);
          return Task.CompletedTask;
      }
}
`,
    "Services/ITeaService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public interface ITeaService
{
      Task<List<Tea>> GetAllAsync();
      Task AddAsync(Tea tea);
      Task UpdateAsync(Tea tea);
      Task DeleteAsync(int id);
}
`,
    "Services/AppServices.cs": `using Microsoft.Extensions.DependencyInjection;

namespace BlazorApp.Services;

// Stands in for Program.cs, which the code box cannot change.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<ITeaService, MemoryTeaService>();
          return services.BuildServiceProvider();
      }
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

### 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`.

      <input @bind="newName" placeholder="Tea name" />
      <input type="number" @bind="newPrice" style="width: 70px" />
      <button @onclick="Add">Add</button>
</p>

@if (teas == null)
{
      <p>Loading...</p>
}
else
{
      @foreach (var tea in teas)
      {
          <p>
              @tea.Name: ₹@tea.Price
              <button @onclick="() => RaisePrice(tea)">+₹5</button>
              <button @onclick="() => Delete(tea.Id)">Delete</button>
          </p>
      }
}

@code {
      // In your app: @inject ITeaService Teas
      private ITeaService Teas = AppServices.Container.GetRequiredService<ITeaService>();
      private List<Tea>? teas;
      private string newName = "";
      private int newPrice = 20;

      protected override async Task OnInitializedAsync() => await Load();

      private async Task Load() => teas = await Teas.GetAllAsync();

      private async Task Add()
      {
          if (newName == "") return;
          await Teas.AddAsync(new Tea { Name = newName, Price = newPrice });  // Create
          newName = "";
          await Load();
      }

      private async Task RaisePrice(Tea tea)
      {
          tea.Price += 5;
          await Teas.UpdateAsync(tea);  // Update
          await Load();
      }

      private async Task Delete(int id)
      {
          await Teas.DeleteAsync(id);   // Delete
          await Load();
      }
}
`,
    "Services/MemoryTeaService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for the EF Core TeaService: same methods, data kept in memory.
public class MemoryTeaService : ITeaService
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public async Task<List<Tea>> GetAllAsync()
      {
          await Task.Delay(500); // pretend to wait for the database
          return teas.OrderBy(t => t.Name).ToList();
      }

      public Task AddAsync(Tea tea)
      {
          tea.Id = nextId++;
          teas.Add(tea);
          return Task.CompletedTask;
      }

      public Task UpdateAsync(Tea tea)
      {
          var old = teas.FirstOrDefault(t => t.Id == tea.Id);
          if (old != null) { old.Name = tea.Name; old.Price = tea.Price; }
          return Task.CompletedTask;
      }

      public Task DeleteAsync(int id)
      {
          teas.RemoveAll(t => t.Id == id);
          return Task.CompletedTask;
      }
}
`,
    "Services/ITeaService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public interface ITeaService
{
      Task<List<Tea>> GetAllAsync();
      Task AddAsync(Tea tea);
      Task UpdateAsync(Tea tea);
      Task DeleteAsync(int id);
}
`,
    "Services/AppServices.cs": `using Microsoft.Extensions.DependencyInjection;

namespace BlazorApp.Services;

// Stands in for Program.cs, which the code box cannot change.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<ITeaService, MemoryTeaService>();
          return services.BuildServiceProvider();
      }
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

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**.

      }
}

@if (editing != null)
{
          <p>New price for @editing.Name: <InputNumber @bind-Value="editing.Price" /></p>
          <button type="submit">Save</button>
}

@code {
      // In your app: @inject ITeaService Teas
      private ITeaService Teas = AppServices.Container.GetRequiredService<ITeaService>();
      private List<Tea>? teas;
      private Tea? editing;

      protected override async Task OnInitializedAsync() => teas = await Teas.GetAllAsync();

      private async Task Save()
      {
          await Teas.UpdateAsync(editing!);   // Update
          editing = null;
          teas = await Teas.GetAllAsync();
      }
}
`,
    "Services/MemoryTeaService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for the EF Core TeaService: same methods, data kept in memory.
public class MemoryTeaService : ITeaService
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public async Task<List<Tea>> GetAllAsync()
      {
          await Task.Delay(500); // pretend to wait for the database
          return teas.OrderBy(t => t.Name).ToList();
      }

      public Task AddAsync(Tea tea)
      {
          tea.Id = nextId++;
          teas.Add(tea);
          return Task.CompletedTask;
      }

      public Task UpdateAsync(Tea tea)
      {
          var old = teas.FirstOrDefault(t => t.Id == tea.Id);
          if (old != null) { old.Name = tea.Name; old.Price = tea.Price; }
          return Task.CompletedTask;
      }

      public Task DeleteAsync(int id)
      {
          teas.RemoveAll(t => t.Id == id);
          return Task.CompletedTask;
      }
}
`,
    "Services/ITeaService.cs": `using BlazorApp.Models;

namespace BlazorApp.Services;

public interface ITeaService
{
      Task<List<Tea>> GetAllAsync();
      Task AddAsync(Tea tea);
      Task UpdateAsync(Tea tea);
      Task DeleteAsync(int id);
}
`,
    "Services/AppServices.cs": `using Microsoft.Extensions.DependencyInjection;

namespace BlazorApp.Services;

// Stands in for Program.cs, which the code box cannot change.
public static class AppServices
{
      public static IServiceProvider Container { get; } = Build();

      private static IServiceProvider Build()
      {
          var services = new ServiceCollection();
          services.AddSingleton<ITeaService, MemoryTeaService>();
          return services.BuildServiceProvider();
      }
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

## Common mistakes

<div className="tscroll">

| 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 |

</div>

## 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**
