ASP.Net Core - Blazor Server App - Scaffolding and Data Access Layer
Building a Blazor Server App with Scaffolding and Data Access Layer
In today's tutorial, we will explore how to create a Blazor Server application using ASP.NET Core and implement a data access layer using scaffolding. This approach leverages the power of Entity Framework Core to streamline database interactions, making it easier to manage data in your applications. We will cover the essentials in a straightforward manner, ensuring you can follow along even if you're new to Blazor and ASP.NET Core.
What is Blazor?
Blazor is a framework for building interactive web applications using C# instead of JavaScript. Blazor Server allows you to build applications that run server-side, sending UI updates to the client over a SignalR connection. This model provides a rich user experience while maintaining a clean separation of concerns.
Prerequisites
Before starting, ensure you have the following installed:
- .NET SDK (version 6.0 or later)
- A code editor (like Visual Studio or Visual Studio Code)
- A SQL Server instance or SQL Server Express
Step 1: Create a New Blazor Server Application
To create a new Blazor Server application, open your command line interface and run:
dotnet new blazorserver -n BlazorDataAccess
This command creates a new Blazor Server app named BlazorDataAccess. Navigate into the project directory:
cd BlazorDataAccess
Step 2: Install Entity Framework Core Packages
Next, we need to install the necessary Entity Framework Core packages to facilitate data access. You can do this by running the following commands:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
These packages will enable us to interact with SQL Server databases and utilize EF Core tools for scaffolding.
Step 3: Create the Data Model
Let's create a simple data model. In the Models folder, create a new class called Product.cs:
namespace BlazorDataAccess.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
This model represents a product with an ID, name, and price.
Step 4: Set Up the DbContext
Next, we need to set up a DbContext to manage our database connections and entities. Create a new class called AppDbContext.cs in the Data folder:
using BlazorDataAccess.Models;
using Microsoft.EntityFrameworkCore;
namespace BlazorDataAccess.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
}
Step 5: Configure the Database Connection
Open the appsettings.json file and add a connection string for your database:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlazorDataAccess;Trusted_Connection=True;"
},
// Other configurations
}
Next, configure the DbContext in Startup.cs:
using BlazorDataAccess.Data;
using Microsoft.EntityFrameworkCore;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddRazorPages();
services.AddServerSideBlazor();
}
Step 6: Scaffold the Data Access Layer
Now, we will scaffold the data access layer. Open your command line and run the following command:
dotnet ef dbcontext scaffold "Server=(localdb)\\mssqllocaldb;Database=BlazorDataAccess;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models
This command generates the data access layer for the Product entity based on the existing database schema.
Step 7: Create a Product Service
Let's create a service to handle product operations. In the Data folder, create a new class called ProductService.cs:
using BlazorDataAccess.Models;
using Microsoft.EntityFrameworkCore;
public class ProductService
{
private readonly AppDbContext _context;
public ProductService(AppDbContext context)
{
_context = context;
}
public async Task<List<Product>> GetProductsAsync()
{
return await _context.Products.ToListAsync();
}
public async Task AddProductAsync(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
}
}
Step 8: Register the Product Service
Now, we need to register the ProductService in Startup.cs:
services.AddScoped<ProductService>();
Step 9: Create the User Interface
Finally, we can create a simple UI to display and add products. Open the Pages folder and modify Index.razor:
@page "/"
@inject ProductService ProductService
<h3>Products</h3>
<ul>
@foreach (var product in products)
{
<li>@product.Name - @product.Price.ToString("C")</li>
}
</ul>
<button @onclick="AddProduct">Add Product</button>
@code {
private List<Product> products = new List<Product>();
protected override async Task OnInitializedAsync()
{
products = await ProductService.GetProductsAsync();
}
private async Task AddProduct()
{
var newProduct = new Product { Name = "New Product", Price = 9.99M };
await ProductService.AddProductAsync(newProduct);
products.Add(newProduct);
}
}
Step 10: Run the Application
Now that everything is set up, run your application using:
dotnet run
Navigate to http://localhost:5000 in your browser, and you should see your Blazor Server application displaying products.
Conclusion
In this tutorial, we explored how to create a Blazor Server application with a data access layer using Entity Framework Core. We set up a simple data model, configured the database context, and created a user interface to interact with our data. Blazor provides a powerful way to build modern web applications with C#, and integrating a data access layer enhances your application's capabilities.
Feel free to expand upon this foundation by adding more features, such as editing and deleting products, and exploring advanced concepts like dependency injection and state management. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment