如何将Blazor WebAssembly连接到数据库
我最近开始开发Blazor WebAssembly应用程序,现在我正在建立数据库连接.
I recently started developing a Blazor WebAssembly app, and now I'm settling on a database connection.
所有课程和说明都表明您需要在Startup.cs文件和appsettings.json中输入信息,但是这些文件不在项目中.
All lessons and instructions say that you need to enter information into the Startup.cs file and appsettings.json, but these files are not in the project.
我不明白.在Blazor WebAssembly中,无法连接到数据库吗?
I do not understand. In Blazor WebAssembly, is there no way to connect to the DB?
不直接.Blazor WebAssembly是一个前端框架.您需要创建一个API控制器来包装数据库连接,并使用HttpClient调用api.一个简单的方法是使用包装实体框架核心数据库上下文的asp.net核心Web api控制器.
Not directly. Blazor WebAssembly is a front end framework. You need to create an API controller to wrap your database connection and use HttpClient to call the api. A straight forward way to do it is to use an asp.net core web api controller wrapping an Entity Framework Core Database context.
@inject HttpClient Http
<template_html_here/>
@code
{
protected override async Task OnInitializedAsync()
{
products = await Http.GetFromJsonAsync<Product[]>("api/Products");
}
}
控制器:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly ProductsDbContext _context; // your database context
public ProductsController(ProductsDbContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<Product> Get()
{
return _context.Products.ToList();
}
}
您可以在 https://docs.microsoft.com/zh-CN/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1 .在 查看更多