.net Core中使用sqlsugar

sqlsugar帮助文档
官网
本文将给出如何使用sqlsugar连接pgsql并实现多租户,具体帮助文档请查看官网

  1. 安装
SqlSugarCore      5.1.4.169   5.1.4.169
  1. 定义一对一,一对多model
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SqlSugarHelperDLL.Models
{//实体//[Tenant("sqlsugar_a")][SugarTable("student")]public class Student{[SugarColumn(IsPrimaryKey = true, IsIdentity = true,ColumnName ="student_id")]public long StudentId { get; set; }[SugarColumn(ColumnName = "name")]public string Name { get; set; }[SugarColumn(ColumnName = "school_id")]public long SchoolId { get; set; }//标准配置 推荐[Navigate(NavigateType.OneToOne, nameof(SchoolId))]//一对一 SchoolId是StudentA类里面的public School School { get; set; } //不能赋值只能是null[Navigate(NavigateType.OneToMany, nameof(Book.studenId))]//BookA表中的studenIdpublic List<Book> Books { get; set; }//注意禁止给books手动赋值//非主键模式 需要手动赋值防止插入0这种默认值//[Navigate(NavigateType.OneToOne, nameof(SchoolId),nameof(SchoolA.Id))] }//[Tenant("sqlsugar_b")][SugarTable(TableName = "school")]public class School{[SugarColumn(IsPrimaryKey = true, IsIdentity = true,ColumnName ="school_id")]public long Id { get; set; }[SugarColumn(ColumnName ="school_name")]public string SchoolName { get; set; }}[SugarTable(TableName = "book")]public class Book{[SugarColumn(IsPrimaryKey = true, IsIdentity = true,ColumnName ="book_id")]public long BookId { get; set; }[SugarColumn(ColumnName ="name")]public string Name { get; set; }public long studenId { get; set; }}
}
  1. 定义helper类
using SqlSugar;
using SqlSugarHelperDLL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SqlSugarHelperDLL
{public class SqlsugarHelper{private readonly ISqlSugarClient _sqlSugarClient;public SqlsugarHelper(ISqlSugarClient sqlSugarClient){_sqlSugarClient = sqlSugarClient;//_sqlSugarClient.MappingTables.Add("studenta", "sqlsugarA.studenta");}// 初始化数据表public void InitTable(){var DB = _sqlSugarClient.AsTenant().GetConnection("sqlsugar_a");Console.WriteLine(_sqlSugarClient.CurrentConnectionConfig.ConnectionString); DB.CodeFirst.InitTables(typeof(Student)); // Supported by all databases  DB.CodeFirst.InitTables(typeof(School));DB.CodeFirst.InitTables(typeof(Book));DB = _sqlSugarClient.AsTenant().GetConnection("sqlsugar_b");DB.CodeFirst.InitTables(typeof(Student)); // Supported by all databases  DB.CodeFirst.InitTables(typeof(School));DB.CodeFirst.InitTables(typeof(Book));}//https://www.donet5.com/Home/Doc?typeId=2430public async void Insert(){List<Student> list = new List<Student>();list.Add(new Student(){Name="ellis",School = new School() { SchoolName = "辽工大"},Books = new List<Book>() { new Book() { Name = "Python"},new Book() { Name = "C#"}, new Book() { Name = ".net Core"} }});var DB = _sqlSugarClient.AsTenant().GetConnection("sqlsugar_a");DB.InsertNav(list).Include(x=>x.School).Include(it => it.Books, new InsertNavOptions(){ OneToManyIfExistsNoInsert = true }).ExecuteCommandAsync();DB = _sqlSugarClient.AsTenant().GetConnection("sqlsugar_b");DB.InsertNav(list).Include(x => x.School).Include(it => it.Books, new InsertNavOptions(){ OneToManyIfExistsNoInsert = true }).ExecuteCommandAsync();}public async Task<Student> Query(int id,string schema){var DB = _sqlSugarClient.AsTenant().GetConnection(schema);return await DB.Queryable<Student>().Includes(x => x.Books).Includes(x => x.School).Where(x => x.StudentId == id).FirstAsync();}//https://github.com/DotNetNext/SqlSugar/wiki/2.2-Dynamic-Updatepublic async Task<int> UpdateByDictionary(int id, string schema,string name){var dt = new Dictionary<string, object>();dt.Add("student_id", id);dt.Add("name", name);var DB = _sqlSugarClient.AsTenant().GetConnection(schema);return await DB.Updateable(dt).AS("student").WhereColumns("student_id").ExecuteCommandAsync();}// 级联更新//https://www.donet5.com/Home/Doc?typeId=2432public async Task<bool> Update(int id, string schema){List<Student> list = new List<Student>();list.Add(new Student(){StudentId = id,Name = "ellis",School = new School() { SchoolName = "lgd",Id=1 }});var DB = _sqlSugarClient.AsTenant().GetConnection(schema);return await DB.UpdateNav(list,new UpdateNavRootOptions() { IgnoreColumns = new string[] {"Name"},//忽略的更新属性IsInsertRoot = true, // 主表不存在就插入IsDisableUpdateRoot = true, //主表不更新IsIgnoreAllNullColumns = true//主表null列不更新}).Include(x => x.School).ExecuteCommandAsync();}//	根据主键删除//https://github.com/DotNetNext/SqlSugar/wiki/4.1-Deletepublic async Task<int> Delete(int id,string schema){var DB = _sqlSugarClient.AsTenant().GetConnection(schema);//by entityreturn await DB.Deleteable<Student>().Where(new Student() { StudentId=id }).ExecuteCommandAsync();//by primary keyDB.Deleteable<Student>().In(id).ExecuteCommand();//by primary key arrayDB.Deleteable<Student>().In(new int[] { 1, 2 }).ExecuteCommand();//by expressionDB.Deleteable<Student>().Where(it => it.StudentId == 1).ExecuteCommand();//delete by SubqueryableDB.Deleteable<Student>().Where(p => p.SchoolId == SqlFunc.Subqueryable<School>().Where(s => s.Id == p.SchoolId).Select(s => s.Id)).ExecuteCommand();}//级联删除public async Task<bool> DeleteByExpression(int id,string schema){var DB = _sqlSugarClient.AsTenant().GetConnection(schema);return await DB.DeleteNav<Student>(stu => stu.StudentId == id).Include(stu => stu.School).Include(stu => stu.Books).ExecuteCommandAsync();}// 分页查询//https://www.donet5.com/Home/Doc?typeId=2242public async Task<List<Student>> PageQuery(string schema,int pagesize,int pagenum){List<OrderByModel> orderList = OrderByModel.Create(new OrderByModel() { FieldName = "student_id", OrderByType = OrderByType.Desc },new OrderByModel() { FieldName = "name" } //默认防注入:并且可以用StaticConfig.Check_FieldFunc重写验证机质);RefAsync<int> totalnumber = 0;var DB = _sqlSugarClient.AsTenant().GetConnection(schema);return await DB.Queryable<Student>().OrderBy(orderList).Includes(x=>x.School).Includes(x=>x.Books).ToPageListAsync(pagenum, pagesize, totalnumber);}//开窗//https://www.donet5.com/Home/Doc?typeId=2243public async Task<List<Student>> OverFunc(string schema){var DB = _sqlSugarClient.AsTenant().GetConnection(schema);// 查询符合条件的学生数据var studentList = await DB.Queryable<Student>().Select(it => new{it.StudentId,it.Name,it.SchoolId,RowNum = SqlFunc.RowNumber(it.StudentId,it.Name)// 使用开窗函数//order by id partition by name//多字段排序  order by id asc ,name desc//SqlFunc.RowNumber($"{it.Id} asc ,{it.Name} desc ",$"{it.Name}")}).MergeTable() // 将子查询的结果合并成一个表.Where(it => it.RowNum == 1) // 只选择 RowNumber 为 1 的记录.Select(it => new Student{StudentId = it.StudentId,Name = it.Name,SchoolId = it.SchoolId}).ToListAsync();// 为每个学生手动加载关联的 School 和 Books 数据foreach (var student in studentList){// 加载关联的 Schoolstudent.School = await DB.Queryable<School>().Where(s => s.Id == student.SchoolId).FirstAsync();// 加载关联的 Books 列表student.Books = await DB.Queryable<Book>().Where(b => b.studenId == student.StudentId).ToListAsync();}return studentList;}}
}
  1. DI
    重要的是需要设置SearchPath,ConfigId以及DbLinkName,其中ConfigId以及DbLinkName需要一致,数据库的schema不能有大写
builder.Services.AddScoped<ISqlSugarClient>(opt => new SqlSugarClient(new List<ConnectionConfig>()
{new ConnectionConfig {ConfigId="sqlsugar_a",DbType= DbType.PostgreSQL,ConnectionString="Host=192.168.214.133;Port=32222;Database=postgresdb;Username=postgresadmin;Password=admin123;SearchPath=sqlsugar_a",DbLinkName="sqlsugar_a",InitKeyType = InitKeyType.Attribute, // 从特性初始化表IsAutoCloseConnection = true, // 自动关闭连接//MoreSettings = new ConnMoreSettings//{//    PgSqlIsAutoToLower = false // 保持表名和列名大小写不变//}},new ConnectionConfig {ConfigId="sqlsugar_b",DbType= DbType.PostgreSQL,ConnectionString="Host=192.168.214.133;Port=32222;Database=postgresdb;Username=postgresadmin;Password=admin123;SearchPath=sqlsugar_b",DbLinkName="sqlsugar_b",InitKeyType = InitKeyType.Attribute, // 从特性初始化表IsAutoCloseConnection = true, // 自动关闭连接//MoreSettings = new ConnMoreSettings//{//    PgSqlIsAutoToLower = false // 保持表名和列名大小写不变//}}}
}));builder.Services.AddScoped<SqlsugarHelper>();
  1. controller
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SqlSugarHelperDLL;
using SqlSugarHelperDLL.Models;namespace SqlSugarAPI.Controllers
{[Route("api/[controller]/[action]")][ApiController]public class SqlSugarController : ControllerBase{private readonly SqlsugarHelper _sqlsugarHelper;public SqlSugarController(SqlsugarHelper sqlsugarHelper){_sqlsugarHelper = sqlsugarHelper;}[HttpGet]public IActionResult InitDB(){_sqlsugarHelper.InitTable();return Ok("suc");}[HttpPost]public IActionResult Insert(){_sqlsugarHelper.Insert();return Ok("suc");}[HttpGet]public async Task<Student> Query([FromQuery] int id,[FromQuery] string schema){return await _sqlsugarHelper.Query(id, schema);}[HttpPut]public async Task<IActionResult> UpdateByDic([FromQuery] int id, [FromQuery] string schema,[FromQuery] string name){int count =  await _sqlsugarHelper.UpdateByDictionary(id, schema,name);return Ok(count);}[HttpPut]public async Task<IActionResult> Update([FromQuery] int id, [FromQuery] string schema){bool count = await _sqlsugarHelper.Update(id, schema);return Ok(count);}[HttpDelete]public async Task<IActionResult> Delete(int id, string schema){var count = await _sqlsugarHelper.Delete(id, schema);return Ok(count);}[HttpDelete]public async Task<IActionResult> DeleteByExpression(int id, string schema){var count = await _sqlsugarHelper.DeleteByExpression(id, schema);return Ok(count);}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/457565.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

c++编解码封装

多态版编解码 对服务器和客户端的结构体进行序列化然后对数据进行反序列化 案例分析 代码demo Codec.h #pragma once #include <iostream>class Codec { public:Codec();virtual std::string encodeMsg();//string是标准库的string类virtual void* decodeMsg();virtu…

西瓜书《机器学习》符号表KaTex表示

写这篇post的缘故是最近整理机器学习的相关公式&#xff0c;经常要用到KaTex, 但网络上搜索到的西瓜书符号表的表示有些并不准确或不严谨&#xff0c;本着严谨治学的态度&#xff0c;整理了一下符号表的KaTex表示&#xff0c;希望有所帮助,整理过程中参考了《南瓜书》和 KaTex官…

Flutter TextField和Button组件开发登录页面案例

In this section, we’ll go through building a basic login screen using the Button and TextField widgets. We’ll follow a step-bystep approach, allowing you to code along and understand each part of the process. Let’s get started! 在本节中&#xff0c;我们…

软件系统建设方案书(word参考模板)

1 引言 1.1 编写目的 1.2 项目概述 1.3 名词解释 2 项目背景 3 业务分析 3.1 业务需求 3.2 业务需求分析与解决思路 3.3 数据需求分析【可选】 4 项目建设总体规划【可选】 4.1 系统定位【可选】 4.2 系统建设规划 5 建设目标 5.1 总体目标 5.2 分阶段目标【可选】 5.2.1 业务目…

ctfshow(259->261)--反序列化漏洞--原生类与更多魔术方法

Web259 进入界面&#xff0c;回显如下&#xff1a; highlight_file(__FILE__);$vip unserialize($_GET[vip]); //vip can get flag one key $vip->getFlag();题干里还提示了网站有一个flag.php界面&#xff0c;源代码如下&#xff1a; $xff explode(,, $_SERVER[HTTP_X…

Docker容器操作

Docker容器操作 启动容器 docker run -it 镜像名(镜像id) bash当利用docker run来创建容器时&#xff0c;Docker在后台运行的标准操作包括&#xff1a; 检查本地是否存在指定的镜像&#xff0c;不存在就从公有仓库中下载利用镜像创建并启动一个容器分配一个文件系统&#xf…

C语言实现Go的defer功能

之前笔者写了一篇博文C实现Go的defer功能&#xff0c;介绍了如何在C语言中实现Go的defer功能&#xff0c;那在C语言中是否也可以实现这样的功能呢&#xff1f;本文就将介绍一下如何在C语言中实现Go的defer功能。 我们还是使用C实现Go的defer功能中的示例&#xff1a; void te…

医院信息化与智能化系统(9)

医院信息化与智能化系统(9) 这里只描述对应过程&#xff0c;和可能遇到的问题及解决办法以及对应的参考链接&#xff0c;并不会直接每一步详细配置 如果你想通过文字描述或代码画流程图&#xff0c;可以试试PlantUML&#xff0c;告诉GPT你的文件结构&#xff0c;让他给你对应的…

改进YOLOv8系列:引入低照度图像增强网络Retinexformer | 优化低光照目标检测那题

改进YOLOv8系列:引入低照度图像增强网络Retinexformer | 优化低光照目标检测那题 🚀论文研究概括🚀加入到网络中的理论研究🚀需要修改的代码1 🍀🍀Retinexformer 代码2🍀🍀tasks里引用🚀创建yaml文件🚀测试是否创建成功前言:这篇论文提出了一种用于低光图像…

STM32应用详解(10)I2C总线初始化

文章目录 前言一、I2C总线初始化二、程序源码与详解1.I2C初始化2.I2C端口初始化及设置IO端口工作模式3.函数I2C_Init4.函数I2C_Cmd5.使能APB1外设时钟6.I2C通信时序图 前言 介绍STM32的I2C总线初始化&#xff0c;给出了代码详解。《i2c.h》文件&#xff0c;由用户编写。定义了…

系统聚类比较——最短距离法、最长距离法、重心法和类平均法

系统聚类概述 系统聚类&#xff0c;又称分层聚类法&#xff0c;是一种用于分析数据的统计方法&#xff0c;在生物学、分类学、社会网络等领域有广泛应用。以下是对系统聚类的详细概述&#xff1a; 一、基本思想 系统聚类的基本思想是将每个样品&#xff08;或数据点&#xf…

OAK相机的RGB-D彩色相机去畸变做对齐

▌低畸变标准镜头的OAK相机RGB-D对齐的方法 OAK相机内置的RGB-D管道会自动将深度图和RGB图对齐。其思想是将深度图像中的每个像素与彩色图像中对应的相应像素对齐。产生的RGB-D图像可以用于OAK内置的图像识别模型将识别到的2D物体自动映射到三维空间中去&#xff0c;或者产生的…

深入理解Python异常处理机制

在Python编程中&#xff0c;异常处理是一个非常重要的概念。它可以帮助我们捕获程序运行过程中出现的错误&#xff0c;防止程序崩溃&#xff0c;并提供友好的错误信息。本文将详细讲解Python的异常处理机制&#xff0c;并提供丰富的代码示例&#xff0c;帮助您更好地理解和应用…

【Spring MVC】响应结果和设置

​ 我的主页&#xff1a;2的n次方_ 1. 返回静态页面 先创建一个 html 页面 ​ 如果还按照之前的方式进行返回的话&#xff0c;返回的并不是一个 html 页面 RequestMapping("/response") RestController public class ResponseController {RequestMapping(&quo…

React基础使用教程

初识JSX React主要使用的就是jsx语法来编写dom&#xff0c;所以我们要先认识jsx&#xff0c;然后再开始学习两者相结合jsx其实就是在JS中编写HTML的一种写法编写jsx要注意以下几个规则&#xff1a; 定义虚拟DOM时&#xff0c;不要写引号标签中混入JS表达式时要用{}样式的类名指…

2024 Rust现代实用教程:1.3获取rust的库国内源以及windows下的操作

文章目录 一、使用Cargo第三方库1.直接修改Cargo.toml2.使用cargo-edit插件3.设置国内源4.与windows下面的rust不同点 参考 一、使用Cargo第三方库 1.直接修改Cargo.toml rust语言的库&#xff1a;crate 黏贴至Cargo.toml 保存完毕之后&#xff0c;自动下载依赖 拷贝crat…

形态学-闭运算

目录 依赖库显示图像的函数读取图像转换为灰度图像应用二值化阈值处理创建结构元素应用形态学闭运算显示结果 依赖库 首先&#xff0c;我们需要导入必要的库&#xff1a; import cv2 import numpy as npcv2 是OpenCV的Python接口&#xff0c;用于图像处理。numpy 是一个用于科…

在时间敏感网络中启用网络诊断:协议、算法和硬件

英文论文标题&#xff1a;Enabling Network Diagnostics in Time-Sensitive Networking: Protocol, Algorithm, and Hardware 作者信息&#xff1a; Zeyu Wang, Xiaowu He, Xiangwen Zhuge, Shen Xu, Fan Dang, Jingao Xu, Zheng Yang所属机构&#xff1a;清华大学软件学院和…

Pytorch笔记--RuntimeError: NCCL communicator was aborted on rank 3.

1--分布式并行训练&#xff0c;出现以下bug&#xff1a; [E ProcessGroupNCCL.cpp:719] [Rank 3] Watchdog caught collective operation timeout: WorkNCCL(SeqNum1721483, OpTypeALLREDUCE, Timeout(ms)1800000) ran for 1805695 milliseconds before timing out. RuntimeErr…

Docker:安装 Syslog-ng 的技术指南

1、简述 Syslog-ng 是一种流行的日志管理工具&#xff0c;能够集中处理和分析日志。通过 Docker 安装 Syslog-ng 可以简化部署和管理过程。本文将介绍如何使用 Docker 安装 Syslog-ng&#xff0c;并提供一个 Java 示例来展示如何将日志发送到 Syslog-ng。 2、安装 2.1 创建…