.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

然后我们运行程序,得到了数据库中的数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值