How to query data from a database in Blazor Server APP(obsolete)
There is a better IDbContextFactory interface: ASP.NET Core Blazor Server with Entity Framework Core (EFCore)
Prerequisites: normal configuration for ASP.NET Core to connect a database.
Models > ToDo.cs
public class ToDo
{
[Key]
public int Id { get; set; }
[Required]
public string Content { get; set; }
public bool IsDone { get; set; }
}
Interfaces > IToDoService.cs
public interface IToDoService
{
public Task<List<ToDo>> GetAsync();
public Task<ToDo> GetAsync(int id);
public Task CreateAsync(ToDo todo);
public Task DeleteAsync(int id);
}
Services > ToDoService.cs
public class ToDoService : IToDoService
{
public ToDoService(ApplicationDbContext context)
{
_context = context;
}
private ApplicationDbContext _context { get; }
public async Task<List<ToDo>> GetAsync()
{
var todos = await _context.ToDos
.OrderBy(x => x.Id)
.ToListAsync();
return todos;
}
public async Task<ToDo> GetAsync(int id)
{
var todo = await _context.ToDos.FindAsync(id);
if (todo is null)
{
return null;
}
else
{
return todo;
}
}
public async Task CreateAsync(ToDo todo)
{
await _context.ToDos.AddAsync(todo);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(int id)
{
var todo = await _context.ToDos.FindAsync(id);
if (todo is not null)
{
_context.ToDos.Remove(todo);
await _context.SaveChangesAsync();
}
}
}
Program.cs
builder.Services.AddScoped<IToDoService, ToDoService>();
Pages > ToDo.razor
@page "/todo"
@inject IToDoService ToDoService
<h3>ToDo</h3>
@if (todos is null)
{
<p>Loading...</p>
}
else
{
<ul class="list-group">
@foreach (var todo in todos)
{
<li class="list-group-item" @key="todo.Id">
<span>@todo.Content</span>
<button class="btn btn-outline-danger btn-sm" @onclick="@(() => Delete(todo.Id))">Delete</button>
</li>
}
</ul>
}
<div class="input-group mt-3">
<input type="text" class="form-control" placeholder="New todo" @bind="nextTodo">
<button class="btn btn-outline-primary" type="button" @onclick="Add" disabled="@adding">@(adding ? "adding..." : "Add New")</button>
</div>
@code {
List<blazorserver.Models.ToDo> todos;
string nextTodo;
bool adding;
protected override async Task OnInitializedAsync()
{
await Get();
}
async Task Get()
{
todos = await ToDoService.GetAsync();
}
async Task Add()
{
if (!string.IsNullOrWhiteSpace(nextTodo.Trim()))
{
var next = new blazorserver.Models.ToDo
{
Content = nextTodo.Trim(),
};
adding = true;
await ToDoService.CreateAsync(next);
nextTodo = string.Empty;
adding = false;
await Get();
}
}
async Task Delete(int id)
{
await ToDoService.DeleteAsync(id);
await Get();
}
}
创建时间:6/26/2022 12:58:11 AM
修改时间:9/29/2022 10:08:54 AM