可以尝试使用 EF Core 来管理数据库访问并实现服务器端应用程序。
示例代码:
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions options) : base(options)
{
}
public DbSet MyEntities { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddScoped();
}
public class MyService
{
private readonly MyDbContext _dbContext;
public MyService(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task GetMyEntity(Guid id)
{
return await _dbContext.MyEntities.FindAsync(id);
}
}
@page "/my-page"
@inject MyService MyService
@if (MyEntity != null)
{
@MyEntity.Name
}
else
{
Loading...
}
@code {
private MyEntity MyEntity;
protected override async Task OnInitializedAsync()
{
MyEntity = await MyService.GetMyEntity(Guid.NewGuid());
}
}