.net8 blazor auto模式很爽(五)读取sqlite并显示(2)

发布于:2024-06-17 ⋅ 阅读:(35) ⋅ 点赞:(0)

在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

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


网站公告

今日签到

点亮在社区的每一天
去签到