DEV Community

Roel
Roel

Posted on

5

How to C#: Creating a simple CRUD page with Blazor and EntityFrameworkCore

Blazor, part of the .NET ecosystem, enables developers to build interactive web applications using C#. In this guide, we'll create a simple CRUD (Create, Read, Update, Delete) application using Blazor and Entity Framework Core in .NET 8.


Prerequisites

  • .NET 8 SDK: Ensure you have the latest .NET 8 SDK installed. You can download it from the official .NET website.

  • Blazor Project: Create a new Blazor Server or WebAssembly project.

  • NuGet Packages: Add the following packages to your project:

  <ItemGroup>
      <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0" />
  </ItemGroup>
Enter fullscreen mode Exit fullscreen mode

Step 1: Set Up the Data Model

Define a simple data model, for example, a Product class:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Create a DbContext to manage the database operations:

public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure the Database Connection

In your appsettings.json, add the connection string:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlazorCrudDb;Trusted_Connection=True;"
  }
}
Enter fullscreen mode Exit fullscreen mode

In Program.cs, register the AppDbContext with the dependency injection container:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Database

Use Entity Framework Core tools to create the database:

  1. Open the Package Manager Console.
  2. Run the following commands:
   Add-Migration InitialCreate
   Update-Database
Enter fullscreen mode Exit fullscreen mode

Step 4: Build the Blazor Components

Create a Blazor component, e.g., ProductList.razor, to handle CRUD operations:

@page "/products"
@inject AppDbContext Context

<h3>Product List</h3>

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var product in products)
        {
            <tr>
                <td>@product.Name</td>
                <td>@product.Price</td>
                <td>
                    <button @onclick="() => EditProduct(product.Id)">Edit</button>
                    <button @onclick="() => DeleteProduct(product.Id)">Delete</button>
                </td>
            </tr>
        }
    </tbody>
</table>

<h3>Add/Edit Product</h3>
<input @bind="currentProduct.Name" placeholder="Name" />
<input @bind="currentProduct.Price" placeholder="Price" />
<button @onclick="SaveProduct">Save</button>

@code {
    private List<Product> products;
    private Product currentProduct = new Product();

    protected override async Task OnInitializedAsync()
    {
        products = await Context.Products.ToListAsync();
    }

    private async Task SaveProduct()
    {
        if (currentProduct.Id == 0)
        {
            Context.Products.Add(currentProduct);
        }
        else
        {
            Context.Products.Update(currentProduct);
        }
        await Context.SaveChangesAsync();
        products = await Context.Products.ToListAsync();
        currentProduct = new Product();
    }

    private void EditProduct(int id)
    {
        currentProduct = products.FirstOrDefault(p => p.Id == id);
    }

    private async Task DeleteProduct(int id)
    {
        var product = await Context.Products.FindAsync(id);
        if (product != null)
        {
            Context.Products.Remove(product);
            await Context.SaveChangesAsync();
            products = await Context.Products.ToListAsync();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Run and Test the Application

Run your Blazor application and navigate to /products. You should be able to add, edit, and delete products, with changes reflected in the database.


Conclusion

You've now created a basic CRUD application using Blazor and Entity Framework Core in .NET 8. This setup provides a solid foundation for building more complex applications.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more