SqlHelper 使用EF-Core框架 连接池处理并发

devtools/2024/10/21 14:37:16/

定义数据库

数据库名称:T_dicomPatientMsg

注意5大约束条件:

1.主键约束:primary key  IDKEY设置为主键,主键设置自增长

2.唯一性约束:unique

3.默认约束:default    所有值都要设置默认值,除了主键

4.检查约束:check

5.外键约束:foreign key

定义实体
 public class DicomPatientMsg{[Key]public int IDKEY { get; set; }        //设为主键,注意实体名称需要与数据库实体名称一致public string PatientID { get; set; }public string PatientName { get; set; }public DateTime PatientBirthDate { get; set; }public DateTime CheckDate { get; set; }public string PicturePath { get; set; }public string DicomFilePath { get; set; }public string SOPInstanceUID { get; set; }public string StudyID { get; set; }public string StudyInstanceUID { get; set; }public string SeriesInstanceUID { get; set; }public string InstanceNum { get; set; }public bool IsDelete { get; set; } }
SQL帮助类

连接池实现并发连接

public class SqlHelper
{private readonly AppDbContext _context;//构造函数注入DB_contextpublic SqlHelper(AppDbContext context){_context = context;}// 增加实体public async Task AddAsync<T>(T entity) where T : class{await _context.Set<T>().AddAsync(entity);await _context.SaveChangesAsync();}// 获取所有实体public async Task<List<T>> GetAllAsync<T>() where T : class{return await _context.Set<T>().ToListAsync();}// 根据ID获取实体public async Task<T> GetByIdAsync<T>(int id) where T : class{return await _context.Set<T>().FindAsync(id);}// 更新实体public async Task UpdateAsync<T>(T entity) where T : class{_context.Set<T>().Update(entity);await _context.SaveChangesAsync();}// 删除实体public async Task DeleteAsync<T>(T entity, bool isDelete = false) where T : class{if (isDelete){_context.Set<T>().Remove(entity);}else{var property = entity.GetType().GetProperty("IsDeleted");if (property != null && property.PropertyType == typeof(bool)){property.SetValue(entity, true);_context.Set<T>().Update(entity);}else{throw new InvalidOperationException("Error");}}await _context.SaveChangesAsync();}
}
 public async Task AddAsync<T>(T entity) where T : class{await _context.Set<T>().AddAsync(entity);await _context.SaveChangesAsync();}

//增加实体

public 表面方法是公开的,所有其他类都可以调用

async 表方法内可能包含异步操作,允许方法在内部使用"await"

await 在异步操作中使用,会暂停当前方法的执行(阻塞当前线程),直到方法执行完成后,才会继续执行下面的代码,暂停期间,控制权会返回给调用方(如UI线程)

Task 当一个 方法的返回类型是Task时,表面这个方法是异步的,但它不返回任何值(即它是'void'的异步版本,同理int的异步版本为Task<int>)。通过Task,调用者可以选择是否等待这个方法完成

AddAsync<T>(T entity)  T是泛型类型的参数,它使得这个方法可以处理任意类型的实体对象。T由调用者传入的entity类型所决定。如果不使用泛型,只处理某一实体类型如User,也可以写成AddUserAsync(User entity)

where T : class  约束条件,限制了T必须是一个类

 private readonly AppDbContext _context;//构造函数注入DB_contextpublic SqlHelper(AppDbContext context){_context = context;}

这里为什么要用构造函数去注入DbContext

DbContext通常代表数据库的会话(增删改查等),每个DbContext实例都代表与数据库的一次交互。

配置AppDbContext
public class AppDbContext : DbContext
{public AppDbContext(DbContextOptions<AppDbContext> options) : base(options){}// 定义数据库表public DbSet<DicomPatientMsg> T_dicomPatientMsg { get;set;}protected override void OnModelCreating(ModelBuilder modelBuilder){modelBuilder.Entity<DicomPatientMsg>().HasQueryFilter(e => !e.IsDelete);        //过滤已软删除的记录}}
在appsettings.json配置数据库连接字符串
{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning","Microsoft.Hosting.Lifetime": "Information"}},"ConnectionStrings": {"DefaultConnection": "Server=.\\SQLEXPRESS;Database=Colposcope;User Id=sa;Password=123;TrustServerCertificate=True;"},"AllowedHosts": "*"
}//TrustServerCertificate=true  禁用SSL验证
注册DbContext 服务
// 从配置文件读取字符串
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");// 添加DbContext服务
builder.Services.AddDbContext<AppDbContext>((options) => options.UseSqlServer(connectionString));//添加SqlHelper,DicomFunc 和控制器类到 DI 容器
builder.Services.AddScoped<SqlHelper>();
builder.Services.AddScoped<DicomFunc>();
使用数据库
private readonly static SqlHelper sqlHelper = SqlHelper.Instance;DicomPatientMsg msg = new DicomPatientMsg()
{DicomFilePath = patientMsg.DicomFilePath,PatientID = patientMsg.PatientID,PatientName = patientMsg.PatientName,CheckDate = checkDate,PicturePath = patientMsg.PicturePath,SOPInstanceUID = dataset.GetString(DicomTag.SOPInstanceUID),StudyID = dataset.GetString(DicomTag.StudyID),StudyInstanceUID = dataset.GetString(DicomTag.StudyInstanceUID),SeriesInstanceUID = dataset.GetString(DicomTag.SeriesInstanceUID),InstanceNum = dataset.GetString(DicomTag.InstanceNumber),
};//存储到sql
await sqlHelper.AddAsync(msg);

下面理清一下这个数据库的使用流程:

1. 依赖链

 DicomController 依赖 DicomFunc,而 DicomFunc 依赖 SqlHelperSqlHelper 又依赖 AppDbContext

  • DicomController 依赖 DicomFunc
  • DicomFunc 依赖 SqlHelper
  • SqlHelper 依赖 AppDbContext

2. 服务注册

  • AppDbContext 的注册:使用 AddDbContext<AppDbContext> 将数据库上下文注册到 DI 容器中。这允许 SqlHelper 构造函数接收 AppDbContext 实例。
  • SqlHelper 的注册:我们使用 AddScoped<SqlHelper>() 注册 SqlHelper,让 DicomFunc 可以注入它。
  • DicomFunc 的注册:我们注册 DicomFunc,确保 DicomController 能够接收它。

3. 依赖注入的执行

当一个请求到达DicomController时,ASP.NET Core的依赖注入容器会

  1. 实例化 DicomController

    控制器依赖于 DicomFunc,容器会尝试实例化 DicomFunc
  2. 实例化 DicomFunc

    DicomFunc 的构造函数依赖于 SqlHelper,容器会进一步尝试实例化 SqlHelper
  3. 实例化 SqlHelper

    SqlHelper 的构造函数依赖于 AppDbContextAppDbContext 是通过 AddDbContext 方法注册到容器中的,它会被自动提供给 SqlHelper
  4. 实例化 AppDbContext

    容器会从依赖注入容器中提取并实例化 AppDbContext,这可能涉及数据库连接的初始化等操作。
  5. 完成实例化

    • 最终,AppDbContext 实例被注入到 SqlHelper 中。
    • SqlHelper 实例被注入到 DicomFunc 中。
    • DicomFunc 实例被注入到 DicomController 中。

http://www.ppmy.cn/devtools/103914.html

相关文章

.Net 6.0--通用帮助类--FileHelper

代码示例 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VW.API.Common.Utils { /// <summary> /// FileHelper 的摘要说明&#xff1a;文件&#xff08;…

力扣刷题--2119. 反转两次的数字【简单】

题目描述 反转 一个整数意味着倒置它的所有位。 例如&#xff0c;反转 2021 得到 1202 。反转 12300 得到 321 &#xff0c;不保留前导零 。 给你一个整数 num &#xff0c;反转 num 得到 reversed1 &#xff0c;接着反转 reversed1 得到 reversed2 。如果 reversed2 等于 nu…

stm32_WS2812B

1结构 实物 内部结构 2引脚与接线 电压特性 引脚意思 脚号符号管脚名功能2DO&#xff08;DOUT&#xff09;数据输出控制信号输出3GND地接地4DI&#xff08;DIN&#xff09;数据输入控制信号输入1VDD电源供电管脚 多个如何接线 3数据传输方法 是如何控制多个的 在硬件连接…

【Linux 从基础到进阶】 Btrfs文件系统配置与优化

Btrfs文件系统配置与优化 引言 Btrfs(B-tree 文件系统)是一个现代的文件系统,旨在提供更高级的功能,如快照、压缩、子卷、数据校验和更强的故障恢复能力。Btrfs被设计为Linux的下一代文件系统,能够在存储管理方面与ZFS竞争。本文将介绍如何在CentOS和Ubuntu系统中配置Bt…

【hot100篇-python刷题记录】【跳跃游戏】

R6-贪心算法 符合贪心的原因是&#xff1a; 我们要走到最后可以每次都选择尽可能远的来走&#xff0c;其次&#xff0c;能走到该步意味着该步以前都能到达。因此&#xff0c;局部最优解可以代表全局最优解。 class Solution:def canJump(self, nums: List[int]) -> bool:#最…

革命性架构:如何用命令模式彻底革新手游后端设计

利用命令模式实现一个手游后端架构是一种将请求封装为对象&#xff0c;从而使得用户可以用不同的请求对客户进行参数化的设计方法。这种方法不仅可以解耦系统的请求发起者和执行者&#xff0c;还支持撤销操作、命令排队和日志记录等功能&#xff0c;极大地提高了系统的灵活性和…

Java程序天生就是多线程程序Java程序天生就是多线程程序吗?

一个Java程序从main()方法开始执行&#xff0c;然后按照既定的代码逻辑执行&#xff0c;看似没有其他线程参与&#xff0c;但实际上Java程序天生就是多线程程序&#xff0c;因为执行main()方法的是一个名称为main的线程。而一个Java程序的运行就算是没有用户自己开启的线程&…

单自由度无阻尼系统振动分析

特别感谢&#xff1a;https://www.bilibili.com/video/BV114411y7ab/?p6&spm_id_frompageDriver&vd_sourceebe07816bf845358030fc92d23830b29 本文图片该系列视频 tips&#xff1a;关于特征方程与振动方程&#xff1a; 特征方程有助于我们理解和确定系统的固有频率和模…