Kết nối cơ sở dữ liệu trong Blazor component

Cần phải thay thế những chiếc pizza được hard-coded hiện tại trong ứng dụng bằng một cơ sở dữ liệu. Bạn có thể sử dụng Microsoft Entity Framework để thêm kết nối vào nguồn dữ liệu. Trong ứng dụng này, chúng ta sẽ sử dụng cơ sở dữ liệu SQLite để lưu trữ pizza.

Trong bài tập này, bạn sẽ thêm các packages để hỗ trợ chức năng cơ sở dữ liệu, kết nối các class với cơ sở dữ liệu back-end và thêm một class trợ giúp để tải trước dữ liệu cho pizza của công ty.

Thêm các packages để hỗ trợ kết nối cơ sở dữ liệu trong Blazor component

1.Trong Visual studio , click phải trên project -> Manage NuGtet Package… -> click tab Browse.

2.search và cài các NuGtet Package sau Microsoft.EntityFrameworkCore, Microsoft.EntityFrameworkCore.Sqlite, System.Net.Http.Json

các Package sẽ được refer trong BlazingPizza.csproj :

<ItemGroup>
<PackageReference Include=”Microsoft.EntityFrameworkCore” Version=”6.0.3″ />
<PackageReference Include=”Microsoft.EntityFrameworkCore.Sqlite” Version=”6.0.3″ />
<PackageReference Include=”System.Net.Http.Json” Version=”6.0.0″ />
</ItemGroup>

Thêm database context và controller

1.Trong Visual studio , click phải trên project -> Add -> New Item

2. chọn Class và đặt tên là PizzaStoreContext.cs –> Add

3.paste code như sau

using Microsoft.EntityFrameworkCore;

namespace BlazingPizza;

public class PizzaStoreContext : DbContext
{
public PizzaStoreContext(DbContextOptions options) : base(options)
{
}

public DbSet<PizzaSpecial> Specials { get; set; }
}

4. tương tự trên tạo thêm class SpecialsController.cs và paste code sau vào

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace BlazingPizza;

[Route(“specials”)]
[ApiController]
public class SpecialsController : Controller
{
private readonly PizzaStoreContext _db;

public SpecialsController(PizzaStoreContext db)
{
_db = db;
}

[HttpGet]
public async Task<ActionResult<List<PizzaSpecial>>> GetSpecials()
{
return (await _db.Specials.ToListAsync()).OrderByDescending(s => s.BasePrice).ToList();
}
}

class này tạo 1 controller cho phép chúng ta lấy dữ liệu từ database cho pizza specials và return về JSON. URL http://localhost:5000/specials.

Khởi tạo data cho SQLite

1. tạo 1 class có tên là SeedData.cs và paste code sau vào

namespace BlazingPizza;

public static class SeedData
{
public static void Initialize(PizzaStoreContext db)
{
var specials = new PizzaSpecial[]
{
new PizzaSpecial()
{
Name = “Basic Cheese Pizza”,
Description = “It’s cheesy and delicious. Why wouldn’t you want one?”,
BasePrice = 9.99m,
ImageUrl = “img/pizzas/cheese.jpg”,
},
new PizzaSpecial()
{
Id = 2,
Name = “The Baconatorizor”,
Description = “It has EVERY kind of bacon”,
BasePrice = 11.99m,
ImageUrl = “img/pizzas/bacon.jpg”,
},
new PizzaSpecial()
{
Id = 3,
Name = “Classic pepperoni”,
Description = “It’s the pizza you grew up with, but Blazing hot!”,
BasePrice = 10.50m,
ImageUrl = “img/pizzas/pepperoni.jpg”,
},
new PizzaSpecial()
{
Id = 4,
Name = “Buffalo chicken”,
Description = “Spicy chicken, hot sauce and bleu cheese, guaranteed to warm you up”,
BasePrice = 12.75m,
ImageUrl = “img/pizzas/meaty.jpg”,
},
new PizzaSpecial()
{
Id = 5,
Name = “Mushroom Lovers”,
Description = “It has mushrooms. Isn’t that obvious?”,
BasePrice = 11.00m,
ImageUrl = “img/pizzas/mushroom.jpg”,
},
new PizzaSpecial()
{
Id = 7,
Name = “Veggie Delight”,
Description = “It’s like salad, but on a pizza”,
BasePrice = 11.50m,
ImageUrl = “img/pizzas/salad.jpg”,
},
new PizzaSpecial()
{
Id = 8,
Name = “Margherita”,
Description = “Traditional Italian pizza with tomatoes and basil”,
BasePrice = 9.99m,
ImageUrl = “img/pizzas/margherita.jpg”,
},
};
db.Specials.AddRange(specials);
db.SaveChanges();
}
}

Lớp sử dụng database context được thông qua, tạo một số đối tượng PizzaSpecial trong một mảng, sau đó lưu chúng vào database .

2. mở file Program.cs và thêm reference đến PizzaStoreContext:

using BlazingPizza;

Tuyên bố này cho phép ứng dụng sử dụng service mới.

3. thêm code sau bên trê app.Run();


// Initialize the database
var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<PizzaStoreContext>();
if (db.Database.EnsureCreated())
{
SeedData.Initialize(db);
}
}

app.Run();

Thay đổi này tạo ra một phạm vi cơ sở dữ liệu với PizzaStoreContext. Nếu chưa có cơ sở dữ liệu nào được tạo, nó sẽ gọi lớp tĩnh SeedData để tạo một cơ sở dữ liệu.

Hiện tại, ứng dụng sẽ không hoạt động vì chúng tôi chưa khởi chạy PizzaStoreContext. Mã này nên được thêm vào Startup.cs.

4.trong Add Services to the container section bên trên của file Program.cs , thêm đoạn code sau

builder.Services.AddHttpClient();
builder.Services.AddSqlite<PizzaStoreContext>(“Data Source=pizza.db”);

sau khi thêm xong code sẽ như sau

using BlazingPizza;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpClient();
builder.Services.AddSqlite<PizzaStoreContext>(“Data Source=pizza.db”);

var app = builder.Build();

….

Mã này đăng ký hai Services. Câu lệnh AddHttpClient đầu tiên cho phép ứng dụng truy cập các lệnh HTTP. Ứng dụng sử dụng HttpClient để nhận JSON cho các món đặc biệt của bánh pizza. Câu lệnh thứ hai đăng ký PizzaStoreContext mới và cung cấp tên file cho cơ sở dữ liệu SQLite.

Hiển thị thông tin pizzas từ database

Giờ đây, chúng ta có thể thay thế bánh pizza được hard-code trong trang index.razor.

1.mở file Page/Index.razor

2. Thay thế phương thức OnInitialized () hiện có bằng:

protected override async Task OnInitializedAsync()
{
specials = await HttpClient.GetFromJsonAsync<List<PizzaSpecial>>(NavigationManager.BaseUri + “specials”);
}

3. Có một số lỗi mà bạn cần phải sửa chữa. Thêm các câu lệnh @inject này dưới chỉ thị @page:

@inject HttpClient HttpClient
@inject NavigationManager NavigationManager

4. mở file  _Imports.razor., thêm code sau và cuối

@using System.Net.Http.Json

5. mở file  Program.cs. thêm đoạn code sau dưới app.MapFallbackToPage(“/_Host”);

app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

6. Start Debugging ,đi đến trang http://localhost:20845/specials

chúng ta sẽ nhận được Json như sau

[{"id":4,"name":"Buffalo chicken","basePrice":12.75,"description":"Spicy chicken, hot sauce and bleu cheese, guaranteed to warm you up","imageUrl":"img/pizzas/meaty.jpg"},{"id":2,"name":"The Baconatorizor","basePrice":11.99,"description":"It has EVERY kind of bacon","imageUrl":"img/pizzas/bacon.jpg"},{"id":7,"name":"Veggie Delight","basePrice":11.5,"description":"It's like salad, but on a pizza","imageUrl":"img/pizzas/salad.jpg"},{"id":5,"name":"Mushroom Lovers","basePrice":11.0,"description":"It has mushrooms. Isn't that obvious?","imageUrl":"img/pizzas/mushroom.jpg"},{"id":3,"name":"Classic pepperoni","basePrice":10.5,"description":"It's the pizza you grew up with, but Blazing hot!","imageUrl":"img/pizzas/pepperoni.jpg"},{"id":1,"name":"Basic Cheese Pizza","basePrice":9.99,"description":"It's cheesy and delicious. Why wouldn't you want one?","imageUrl":"img/pizzas/cheese.jpg"},{"id":8,"name":"Margherita","basePrice":9.99,"description":"Traditional Italian pizza with tomatoes and basil","imageUrl":"img/pizzas/margherita.jpg"}]

quay lại trang chủ http://localhost:20845/

JSON có các loại pizza được liệt kê theo thứ tự giá giảm dần như được chỉ định trong bộ điều khiển bánh pizza đặc biệt.

5-more-blazing-pizzas

Như vậy chúng ta đã hoàn thành bài Kết nối cơ sở dữ liệu trong Blazor component, trong bài kế tiếp chúng ta sẽ tìm hiểu về Cách chia sẻ thông tin giữa các component trong Blazor .

Theo: https://docs.microsoft.com/en-us/learn/modules/interact-with-data-blazor-web-apps/5-exercise-access-data-from-blazor-components

One thought on “Kết nối cơ sở dữ liệu trong Blazor component

  1. Pingback: Chia sẻ data giữa các components trong Blazor applications | Phạm Duy Anh

Leave a Reply

Your email address will not be published.