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


    在BlazorApp1增加文件夹data,里面增加类dbcont

    1. using SharedLibrary.Models;
    2. using System.Collections.Generic;
    3. using Microsoft.EntityFrameworkCore;
    4. namespace BlazorApp1.data
    5. {
    6. public class dbcont : DbContext
    7. {
    8. public dbcont(DbContextOptions options)
    9. : base(options)
    10. {
    11. }
    12. public virtual DbSet<employee> employee { get; set; }
    13. protected override void OnModelCreating(ModelBuilder modelBuilder)
    14. {
    15. // 配置主键
    16. // modelBuilder.Entity().HasKey(e => e.Id);
    17. // 或者对于没有主键的实体(仅适用于特定场景)
    18. modelBuilder.Entity().HasNoKey();
    19. base.OnModelCreating(modelBuilder);
    20. }
    21. }
    22. }

    在BlazorApp1的Program增加下面的代码:

    1. //新增2 添加数据库连接
    2. // 初始化 SQLite 提供程序
    3. string connectionString = "Data Source=cellsmanage6.db3";
    4. builder.Services.AddDbContext(options =>
    5. options.UseSqlite(connectionString, b => b.UseRelationalNulls(true)));
    6. //新增2 结束
    7. builder.Services.AddScoped();

    SharedLibrary的Repositories增加IEmployeeRepository

    1. using SharedLibrary.Models;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Text;
    6. using System.Threading.Tasks;
    7. namespace SharedLibrary.Repositories
    8. {
    9. public interface IEmployeeRepository
    10. {
    11. Task> GetEmployeesAsync();
    12. }
    13. }

    在Client的Services里增加EmployeeService

    1. using SharedLibrary.Models;
    2. using SharedLibrary.Repositories;
    3. using System.Net.Http.Json;
    4. namespace BlazorApp1.Client.Services
    5. {
    6. public class EmployeeService: IEmployeeRepository
    7. {
    8. private readonly HttpClient _httpClient;
    9. public EmployeeService(HttpClient httpClient)
    10. {
    11. _httpClient = httpClient;
    12. }
    13. public async Task<List<employee>> GetEmployeesAsync()
    14. {
    15. return await _httpClient.GetFromJsonAsync>("api/Employee/Getemployee");
    16. }
    17. }
    18. }

    在Client的Program里面增加

    builder.Services.AddScoped();

    在Client的_Imports增加

    @inject IEmployeeRepository EmployeeService

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

  • 相关阅读:
    ffplay源码分析:音视频同步
    Springboot实现ENC加密
    计算机网络 划分子网 ICMP DHCP
    AI的Prompt是什么
    MCE 虚拟筛选、小分子化合物库
    方案:AI赋能,森林防火可视化智能监管与风险预警系统解决方案
    java若依框架代码生成工具使用(前后端分离版)
    速码!!BGP最全学习笔记:BGP概述
    Oracle自定义函数实现递归查询(用自定义函数替换connect_by_root)
    网络安全的「生意经」不好讲
  • 原文地址:https://blog.csdn.net/mrdzhu/article/details/139624567