本文主要是介绍.net8 blazor auto模式很爽(五)读取sqlite并显示(2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在BlazorApp1增加文件夹data,里面增加类dbcont
using SharedLibrary.Models;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;namespace BlazorApp1.data
{public class dbcont : DbContext{public dbcont(DbContextOptions<dbcont> options): base(options){}public virtual DbSet<employee> employee { get; set; }protected override void OnModelCreating(ModelBuilder modelBuilder){// 配置主键// modelBuilder.Entity<employee>().HasKey(e => e.Id);// 或者对于没有主键的实体(仅适用于特定场景)modelBuilder.Entity<employee>().HasNoKey();base.OnModelCreating(modelBuilder);}}
}
在BlazorApp1的Program增加下面的代码:
//新增2 添加数据库连接
// 初始化 SQLite 提供程序
string connectionString = "Data Source=cellsmanage6.db3";
builder.Services.AddDbContext<dbcont>(options =>options.UseSqlite(connectionString, b => b.UseRelationalNulls(true)));
//新增2 结束
builder.Services.AddScoped<IEmployeeRepository, EmployeeService>();
在SharedLibrary的Repositories增加IEmployeeRepository
using SharedLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SharedLibrary.Repositories
{public interface IEmployeeRepository{Task<List<employee>> GetEmployeesAsync();}
}
在Client的Services里增加EmployeeService
using SharedLibrary.Models;
using SharedLibrary.Repositories;
using System.Net.Http.Json;namespace BlazorApp1.Client.Services
{public class EmployeeService: IEmployeeRepository{private readonly HttpClient _httpClient;public EmployeeService(HttpClient httpClient){_httpClient = httpClient;}public async Task<List<employee>> GetEmployeesAsync(){return await _httpClient.GetFromJsonAsync<List<employee>>("api/Employee/Getemployee");}}
}
在Client的Program里面增加
builder.Services.AddScoped<IEmployeeRepository, EmployeeService>();
在Client的_Imports增加
@inject IEmployeeRepository EmployeeService
然后我们运行程序,得到了数据库中的数据
这篇关于.net8 blazor auto模式很爽(五)读取sqlite并显示(2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!