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>
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; }
}
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) { }
}
Step 2: Configure the Database Connection
In your appsettings.json
, add the connection string:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=BlazorCrudDb;Trusted_Connection=True;"
}
}
In Program.cs
, register the AppDbContext
with the dependency injection container:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Step 3: Create the Database
Use Entity Framework Core tools to create the database:
- Open the Package Manager Console.
- Run the following commands:
Add-Migration InitialCreate
Update-Database
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();
}
}
}
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.
Source link
lol