• Net Core 3.1 实现SqlSugar多库操作


    目录

    一、前言

    二、关于SqlSugar

    三、功能实现

    1.项目创建

     2.Nuget管理包引入

    3.数据表实体类创建

    4.仓储

    5.appsettings数据读取

    6.数据库连接配置

    7.SqlSugar IOC注入

     8.仓储注入

    9.Controller创建

     10.启动接口,验证数据连接及数据表的创建


    一、前言

    在开发过程中,会经常用到跨库查询的问题,对于相同类型的数据库,只需要添加一个数据连接,但是对于不同类型的数据库,还需要搭建不同数据库的环境,不论从开发效率还是项目后期维护方面,都是有诸多不便的,那么推荐使用SqlSugar实现多库(多租户

    二、关于SqlSugar

    SqlSugar是一款 老牌 .NET 开源ORM框架

    •  .NET中唯一【全自动分表组件】+【读写分离】+【SAAS分库+多库事务+差异日志】+【大数据读写】 官方完美整合的ORM框架
    •  支持【低代码】+工作流
    • 拥有重多【成熟案例】和良好的【生态】 
    • 支持.NET 百万级【大数据】写入、更新和读取 
    • 使用【最简单】,语法最爽的ORM、仓储、UnitOfWork、DbContext、丰富表达式AOP 
    •  支持 DbFirst、CodeFirst和【WebFirst】 3种模式开发
    • Github star 数 仅次于EF 和 Dapper,每月nuget下载量超过1万
    • 简单易用、功能齐全、高性能、轻量级、服务齐全、官网教程文档、有专业技术支持一天18小时服务
    • 支持关系数据库:MySql、SqlServer、Sqlite、Oracle 、 postgresql、达梦、人大金仓、神通数据库、瀚高、Access 、MySqlConnector、华为 GaussDB、自定义扩展
    • 支持时序数据库:QuestDb 适合 几十亿数据分析统计、分表(性能最强时序数据库) 

    关于SqlSugar的教程及详细使用请参见SqlSugar ORM 5.X 官网 、文档、教程 - SqlSugar 5x - .NET果糖网 

    三、功能实现

    1.项目创建

    创建.net core WebApi项目,创建项目结构如下

     项目结构说明:

     MySqlsugar:api接口

           Common:通用方法,包括仓储注入、数据库实例化、appsettings配置读取等

           Controller:接口文件

    Sqlsugar.Business:业务类库

           Models:数据表实体类

           Repository:业务仓储

           ShareDomain:枚举、Dto等数据

     2.Nuget管理包引入

     1)在Sqlsugar.Business项目中引入SqlSugar.IOC、SqlSugarCore

     2)在MySqlsugar项目中引入System.Linq.Dynamic.Core

     

    3)MySqlsugar项目添加对 Sqlsugar.Business项目的引用

    3.数据表实体类创建

    Models目录下创建

    数据表基类

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using SqlSugar;
    5. namespace Sqlsugar.Business.Models
    6. {
    7. ///
    8. /// 基类
    9. ///
    10. public class BaseEntity
    11. {
    12. public BaseEntity()
    13. {
    14. CreateTime = DateTime.Now;
    15. IsDeleted = false;
    16. }
    17. ///
    18. /// 主键ID
    19. ///
    20. [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    21. public long Id { get; set; }
    22. ///
    23. /// 创建人
    24. ///
    25. [SugarColumn(IsOnlyIgnoreUpdate = true)]
    26. public string CreateBy { get; set; }
    27. ///
    28. /// 创建时间
    29. ///
    30. [SugarColumn(IsOnlyIgnoreUpdate = true)]
    31. public DateTime CreateTime { get; set; }
    32. ///
    33. /// 修改人
    34. ///
    35. [SugarColumn(IsOnlyIgnoreInsert = true, IsNullable = true)]
    36. public string ModifyBy { get; set; }
    37. ///
    38. /// 修改时间
    39. ///
    40. [SugarColumn(IsOnlyIgnoreInsert = true, IsNullable = true)]
    41. public DateTime? ModifyTime { get; set; }
    42. ///
    43. /// 是否删除
    44. ///
    45. public bool IsDeleted { get; set; }
    46. }
    47. }

    分别创建人员、菜单、图书信息三个数据表实体

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using SqlSugar;
    5. namespace Sqlsugar.Business.Models
    6. {
    7. ///
    8. /// 用户信息表
    9. ///
    10. [SugarTable("Sys_UserInfo")]
    11. [Tenant("0")]
    12. public class UserInfo:BaseEntity
    13. {
    14. ///
    15. /// 登录名
    16. ///
    17. public string LoginName { get; set; }
    18. ///
    19. /// 密码
    20. ///
    21. public string PassWord { get; set; }
    22. ///
    23. /// 姓名/昵称
    24. ///
    25. public string UserName { get; set; }
    26. ///
    27. /// 电子邮箱
    28. ///
    29. [SugarColumn(IsNullable = true)]
    30. public string Email { get; set; }
    31. ///
    32. /// 联系电话
    33. ///
    34. [SugarColumn(IsNullable = true)]
    35. public string PhoneNum { get; set; }
    36. ///
    37. /// 出生日期
    38. ///
    39. [SugarColumn(IsNullable = true, ColumnDataType = "date")]
    40. public DateTime? BirthDate { get; set; }
    41. ///
    42. /// 岗位/职位
    43. ///
    44. [SugarColumn(IsNullable = true)]
    45. public string Post { get; set; }
    46. ///
    47. /// 部门
    48. ///
    49. [SugarColumn(IsNullable = true)]
    50. public long? DeptID { get; set; }
    51. ///
    52. /// 角色
    53. ///
    54. [SugarColumn(IsNullable = true, ColumnDataType = "nvarchar(max)")]
    55. public string RoleIds { get; set; }
    56. ///
    57. /// 密码错误次数
    58. ///
    59. [SugarColumn(IsNullable = true)]
    60. public int? ErrorCount { get; set; }
    61. ///
    62. /// 锁定时间
    63. ///
    64. [SugarColumn(IsNullable = true)]
    65. public DateTime? LockTime { get; set; }
    66. }
    67. }
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using SqlSugar;
    5. namespace Sqlsugar.Business.Models
    6. {
    7. ///
    8. /// 菜单信息表
    9. ///
    10. [SugarTable("Sys_Menu")]
    11. [Tenant("0")]
    12. public class Menu:BaseEntity
    13. {
    14. ///
    15. /// 菜单名称
    16. ///
    17. public string MenuName { get; set; }
    18. ///
    19. /// 路径
    20. ///
    21. [SugarColumn(IsNullable =true)]
    22. public string MenuPath { get; set; }
    23. }
    24. }
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using SqlSugar;
    5. namespace Sqlsugar.Business.Models
    6. {
    7. ///
    8. /// 图书信息
    9. ///
    10. [SugarTable("B_BookInfo")]
    11. [Tenant("1")]
    12. public class BookInfo:BaseEntity
    13. {
    14. ///
    15. /// 图书名称
    16. ///
    17. public string BookName { get; set; }
    18. ///
    19. /// 作者
    20. ///
    21. public string Author { get; set; }
    22. }
    23. }

    4.仓储

    创建BaseRepository

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using System.Linq;
    5. using System.Reflection;
    6. using System.Linq.Expressions;
    7. using Sqlsugar.Business.Models;
    8. using Sqlsugar.Business.ShareDomain;
    9. using SqlSugar;
    10. using SqlSugar.IOC;
    11. namespace Sqlsugar.Business.Repository
    12. {
    13. ///
    14. /// 基类仓储
    15. ///
    16. ///
    17. public class BaseRepository<T> : SimpleClient<T> where T : BaseEntity, new()
    18. {
    19. public ITenant itenant = null;//多租户事务
    20. public BaseRepository(ISqlSugarClient context = null) : base(context)
    21. {
    22. //通过特性拿到ConfigId
    23. var configId = typeof(T).GetCustomAttribute()?.configId;
    24. if (configId != null)
    25. {
    26. Context = DbScoped.SugarScope.GetConnectionScope(configId);//根据类传入的ConfigId自动选择
    27. }
    28. else
    29. {
    30. Context = context ?? DbScoped.SugarScope.GetConnectionScope(0);//没有默认db0
    31. }
    32. itenant = DbScoped.SugarScope;//处理多租户事务、GetConnection、IsAnyConnection等功能
    33. CreateDB(Context,configId.ToString());
    34. }
    35. private void CreateDB(ISqlSugarClient client,string configID)
    36. {
    37. client.DbMaintenance.CreateDatabase();//没有数据库的时候创建数据库
    38. var tableLists = client.DbMaintenance.GetTableInfoList();
    39. var files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "Sqlsugar.Business.dll");
    40. if (files.Length > 0)
    41. {
    42. //Type[] types = Assembly.LoadFrom(files[0]).GetTypes().Where(it => it.BaseType == typeof(BaseEntity)).ToArray();
    43. Type[] types = Assembly.LoadFrom(files[0]).GetTypes().Where(it => it.BaseType == typeof(BaseEntity)&& it.GetCustomAttribute().configId.ToString()==configID).ToArray();
    44. foreach (var entityType in types)
    45. {
    46. //创建数据表
    47. string tableName = entityType.GetCustomAttribute().TableName;//根据特性获取表名称
    48. //var configid = entityType.GetCustomAttribute()?.configId;//根据特性获取租户id
    49. //configid = configid == null ? "0" : configid.ToString();
    50. if (!tableLists.Any(p => p.Name == tableName))
    51. {
    52. //创建数据表包括字段更新
    53. client.CodeFirst.InitTables(entityType);
    54. }
    55. }
    56. }
    57. }
    58. ///
    59. /// 新增
    60. ///
    61. ///
    62. ///
    63. public bool Add(T t)
    64. {
    65. try
    66. {
    67. int rowsAffect = Context.Insertable(t).IgnoreColumns(true).ExecuteCommand();
    68. return rowsAffect > 0;
    69. }
    70. catch (Exception ex)
    71. {
    72. return false;
    73. }
    74. }
    75. ///
    76. /// 批量新增
    77. ///
    78. ///
    79. ///
    80. public bool Insert(List t)
    81. {
    82. try
    83. {
    84. int rowsAffect = Context.Insertable(t).ExecuteCommand();
    85. return rowsAffect > 0;
    86. }
    87. catch (Exception ex)
    88. {
    89. return false;
    90. }
    91. }
    92. ///
    93. /// 插入设置列数据
    94. ///
    95. ///
    96. ///
    97. ///
    98. ///
    99. public bool Insert(T parm, Expressionobject>> iClumns = null, bool ignoreNull = true)
    100. {
    101. try
    102. {
    103. int rowsAffect = Context.Insertable(parm).InsertColumns(iClumns).IgnoreColumns(ignoreNullColumn: ignoreNull).ExecuteCommand();
    104. return rowsAffect > 0;
    105. }
    106. catch (Exception ex)
    107. {
    108. return false;
    109. }
    110. }
    111. ///
    112. /// 更新
    113. ///
    114. ///
    115. ///
    116. ///
    117. public bool Update(T entity, bool ignoreNullColumns = false)
    118. {
    119. try
    120. {
    121. int rowsAffect = Context.Updateable(entity).IgnoreColumns(ignoreNullColumns).ExecuteCommand();
    122. return rowsAffect >= 0;
    123. }
    124. catch (Exception ex)
    125. {
    126. return false;
    127. }
    128. }
    129. ///
    130. /// 根据实体类更新指定列 eg:Update(dept, it => new { it.Status });只更新Status列,条件是包含
    131. ///
    132. ///
    133. ///
    134. ///
    135. ///
    136. public bool Update(T entity, Expressionobject>> expression, bool ignoreAllNull = false)
    137. {
    138. try
    139. {
    140. int rowsAffect = Context.Updateable(entity).UpdateColumns(expression).IgnoreColumns(ignoreAllNull).ExecuteCommand();
    141. return rowsAffect >= 0;
    142. }
    143. catch (Exception ex)
    144. {
    145. return false;
    146. }
    147. }
    148. ///
    149. /// 根据实体类更新指定列 eg:Update(dept, it => new { it.Status }, f => depts.Contains(f.DeptId));只更新Status列,条件是包含
    150. ///
    151. ///
    152. ///
    153. ///
    154. ///
    155. public bool Update(T entity, Expressionobject>> expression, Expressionbool>> where)
    156. {
    157. try
    158. {
    159. int rowsAffect = Context.Updateable(entity).UpdateColumns(expression).Where(where).ExecuteCommand();
    160. return rowsAffect >= 0;
    161. }
    162. catch (Exception ex)
    163. {
    164. return false;
    165. }
    166. }
    167. ///
    168. /// 更新指定列 eg:Update(w => w.NoticeId == model.NoticeId, it => new SysNotice(){ UpdateTime = DateTime.Now, Title = "通知标题" });
    169. ///
    170. ///
    171. ///
    172. ///
    173. public bool Update(Expressionbool>> where, Expression> columns)
    174. {
    175. try
    176. {
    177. int rowsAffect = Context.Updateable().SetColumns(columns).Where(where).RemoveDataCache().ExecuteCommand();
    178. return rowsAffect >= 0;
    179. }
    180. catch (Exception ex)
    181. {
    182. return false;
    183. }
    184. }
    185. ///
    186. /// 事务 eg:var result = UseTran(() =>{SysRoleRepository.UpdateSysRole(sysRole);DeptService.DeleteRoleDeptByRoleId(sysRole.ID);DeptService.InsertRoleDepts(sysRole);});
    187. ///
    188. ///
    189. ///
    190. public bool UseTran(Action action)
    191. {
    192. try
    193. {
    194. var result = Context.Ado.UseTran(() => action());
    195. return result.IsSuccess;
    196. }
    197. catch (Exception ex)
    198. {
    199. Context.Ado.RollbackTran();
    200. return false;
    201. }
    202. }
    203. ///
    204. /// 删除
    205. ///
    206. /// 主键id
    207. /// 是否真删除
    208. ///
    209. public bool Delete(object[] ids, bool IsDelete = false)
    210. {
    211. int rowsAffect = 0;
    212. try
    213. {
    214. if (IsDelete)
    215. {
    216. rowsAffect = Context.Deleteable().In(ids).ExecuteCommand();
    217. }
    218. else
    219. {
    220. //假删除 实体属性有isdelete或者isdeleted 请升级到5.0.4.9+,(5.0.4.3存在BUG)
    221. rowsAffect = Context.Deleteable().In(ids).IsLogic().ExecuteCommand();
    222. }
    223. return rowsAffect >= 0;
    224. }
    225. catch (Exception ex)
    226. {
    227. return false;
    228. }
    229. }
    230. ///
    231. /// 根据id获取数据
    232. ///
    233. /// 主键值
    234. /// 泛型实体
    235. public T GetEntityById(long id)
    236. {
    237. return Context.Queryable().First(p => p.Id == id);
    238. }
    239. ///
    240. /// 数据是否存在
    241. ///
    242. ///
    243. ///
    244. public bool IsExists(Expressionbool>> expression)
    245. {
    246. return Context.Queryable().Where(expression).Any();
    247. }
    248. ///
    249. /// 获取所有数据
    250. ///
    251. ///
    252. public List<T> GetAll()
    253. {
    254. return Context.Queryable().ToList();
    255. }
    256. ///
    257. /// 根据查询条件获取数据
    258. ///
    259. ///
    260. ///
    261. public List<T> GetListByWhere(Expressionbool>> expression)
    262. {
    263. return Context.Queryable().Where(expression).ToList();
    264. }
    265. ///
    266. /// 根据查询条件获取数据
    267. ///
    268. ///
    269. /// 排序字段
    270. /// 排序方式
    271. ///
    272. public List GetList(Expressionbool>> expression, Expressionobject>> orderFiled, OrderByType orderEnum = OrderByType.Asc)
    273. {
    274. return Context.Queryable().Where(expression).OrderByIF(orderEnum == OrderByType.Asc, orderFiled, OrderByType.Asc).OrderByIF(orderEnum == OrderByType.Desc, orderFiled, OrderByType.Desc).ToList();
    275. }
    276. ///
    277. /// 获取分页数据
    278. ///
    279. ///
    280. ///
    281. ///
    282. ///
    283. public PagedInfo GetPageList(Expressionbool>> expression, int pageIndex, int PageSize)
    284. {
    285. int totalCount = 0;
    286. var result = Context.Queryable().Where(expression).ToPageList(pageIndex, PageSize, ref totalCount);
    287. var pageResult = new PagedInfo();
    288. pageResult.Result = result;
    289. pageResult.TotalNum = totalCount;
    290. return pageResult;
    291. }
    292. ///
    293. /// 获取分页数据
    294. ///
    295. ///
    296. ///
    297. ///
    298. ///
    299. public PagedInfo GetPageListAsync(Expressionbool>> expression, int pageIndex, int PageSize)
    300. {
    301. RefAsync<int> totalCount = 0;
    302. var result = Context.Queryable().Where(expression).ToPageListAsync(pageIndex, PageSize, totalCount);
    303. var pageResult = new PagedInfo();
    304. pageResult.Result = result.Result;
    305. pageResult.TotalNum = totalCount;
    306. return pageResult;
    307. }
    308. ///
    309. /// 获取分页数据
    310. ///
    311. ///
    312. ///
    313. ///
    314. ///
    315. ///
    316. ///
    317. public PagedInfo GetPageList(Expressionbool>> expression, int pageIndex, int PageSize, Expressionobject>> orderFiled, OrderByType orderEnum = OrderByType.Asc)
    318. {
    319. int totalCount = 0;
    320. var result = Context.Queryable().Where(expression).OrderByIF(orderEnum == OrderByType.Asc, orderFiled, OrderByType.Asc).OrderByIF(orderEnum == OrderByType.Desc, orderFiled, OrderByType.Desc)
    321. .ToPageList(pageIndex, PageSize, ref totalCount);
    322. var pageResult = new PagedInfo();
    323. pageResult.Result = result;
    324. pageResult.TotalNum = totalCount;
    325. return pageResult;
    326. }
    327. ///
    328. /// 获取分页数据
    329. ///
    330. ///
    331. ///
    332. ///
    333. ///
    334. ///
    335. ///
    336. public PagedInfo GetPageListAsync(Expressionbool>> expression, int pageIndex, int PageSize, Expressionobject>> orderFiled, OrderByType orderEnum = OrderByType.Asc)
    337. {
    338. RefAsync<int> totalCount = 0;
    339. var result = Context.Queryable().Where(expression).OrderByIF(orderEnum == OrderByType.Asc, orderFiled, OrderByType.Asc).OrderByIF(orderEnum == OrderByType.Desc, orderFiled, OrderByType.Desc)
    340. .ToPageListAsync(pageIndex, PageSize, totalCount);
    341. var pageResult = new PagedInfo();
    342. pageResult.Result = result.Result;
    343. pageResult.TotalNum = totalCount;
    344. return pageResult;
    345. }
    346. }
    347. }

    分别创建用户和图书的仓储

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using Sqlsugar.Business.Models;
    5. namespace Sqlsugar.Business.Repository
    6. {
    7. public class UserInfoRepository:BaseRepository<UserInfo>
    8. {
    9. ///
    10. /// 保存数据
    11. ///
    12. ///
    13. ///
    14. ///
    15. public bool Save(UserInfo item, string userid)
    16. {
    17. var model = GetById(item.Id);
    18. if (model == null)
    19. {
    20. item.CreateTime = DateTime.Now;
    21. item.CreateBy = userid;
    22. return Add(item);
    23. }
    24. else
    25. {
    26. item.ModifyBy = userid;
    27. item.ModifyTime = DateTime.Now;
    28. return Update(item, false);
    29. }
    30. }
    31. ///
    32. /// 获取用户信息
    33. ///
    34. ///
    35. ///
    36. public UserInfo GetEntity(long id)
    37. {
    38. return GetById(id);
    39. }
    40. }
    41. }
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using Sqlsugar.Business.Models;
    5. namespace Sqlsugar.Business.Repository
    6. {
    7. public class BookInfoRepository : BaseRepository<BookInfo>
    8. {
    9. ///
    10. /// 保存数据
    11. ///
    12. ///
    13. ///
    14. ///
    15. public bool Save(BookInfo item, string userid)
    16. {
    17. var model = GetById(item.Id);
    18. if (model == null)
    19. {
    20. item.CreateTime = DateTime.Now;
    21. item.CreateBy = userid;
    22. return Add(item);
    23. }
    24. else
    25. {
    26. item.ModifyBy = userid;
    27. item.ModifyTime = DateTime.Now;
    28. return Update(item, false);
    29. }
    30. }
    31. ///
    32. /// 获取用户信息
    33. ///
    34. ///
    35. ///
    36. public BookInfo GetEntity(long id)
    37. {
    38. return GetById(id);
    39. }
    40. }
    41. }

    5.appsettings数据读取

     MySqlsugar中Common中创建AppSettings.cs

    1. using Microsoft.Extensions.Configuration;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Threading.Tasks;
    6. namespace MySqlsugar.Common
    7. {
    8. public class AppSettings
    9. {
    10. static IConfiguration Configuration { get; set; }
    11. public AppSettings(IConfiguration configuration)
    12. {
    13. Configuration = configuration;
    14. }
    15. ///
    16. /// 封装要操作的字符
    17. ///
    18. /// 节点配置
    19. ///
    20. public static string App(params string[] sections)
    21. {
    22. try
    23. {
    24. if (sections.Any())
    25. {
    26. return Configuration[string.Join(":", sections)];
    27. }
    28. }
    29. catch (Exception ex)
    30. {
    31. Console.WriteLine(ex.Message);
    32. }
    33. return "";
    34. }
    35. ///
    36. /// 递归获取配置信息数组
    37. ///
    38. ///
    39. ///
    40. ///
    41. public static List<T> App<T>(params string[] sections)
    42. {
    43. List list = new List();
    44. // 引用 Microsoft.Extensions.Configuration.Binder 包
    45. Configuration.Bind(string.Join(":", sections), list);
    46. return list;
    47. }
    48. public static T Bind<T>(string key, T t)
    49. {
    50. Configuration.Bind(key, t);
    51. return t;
    52. }
    53. public static T GetAppConfig<T>(string key, T defaultValue = default)
    54. {
    55. T setting = (T)Convert.ChangeType(Configuration[key], typeof(T));
    56. var value = setting;
    57. if (setting == null)
    58. value = defaultValue;
    59. return value;
    60. }
    61. ///
    62. /// 获取配置文件
    63. ///
    64. /// eg: WeChat:Token
    65. ///
    66. public static string GetConfig(string key)
    67. {
    68. return Configuration[key];
    69. }
    70. }
    71. }

    Startup.cs中配置

     

    6.数据库连接配置

    在appsettings.json中添加数据库连接配置

    1. /*数据库连接配置
    2. ConnectionString:连接字符串
    3. DbType:数据库类型 支持MySql = 0,SqlServer = 1,Sqlite = 2,Oracle = 3,PostgreSQL = 4,Dm = 5,Kdbndp = 6,Oscar = 7,MySqlConnector = 8,Access = 9,OpenGauss = 10,Custom = 900
    4. ConfigId:租户id
    5. IsAutoCloseConnection:自动释放和关闭数据库连接,如果有事务事务结束时关闭,否则每次操作后关闭
    6. */
    7. "ConnectionConfigs": [
    8. {
    9. "ConnectionString": "Data Source=.;User ID=sa;Password=123456;Initial Catalog=AdminManage",
    10. "DbType": 1,
    11. "ConfigId": "0",
    12. "IsAutoCloseConnection": true
    13. },
    14. {
    15. "ConnectionString": "Data Source=.;User ID=sa;Password=123456;Initial Catalog=Book",
    16. "DbType": 1,
    17. "ConfigId": "1",
    18. "IsAutoCloseConnection": true
    19. }
    20. ]

    7.SqlSugar IOC注入

    在Common中创建SqlsugarSetup.cs

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Linq.Expressions;
    5. using System.Threading.Tasks;
    6. using System.Reflection;
    7. using SqlSugar;
    8. using SqlSugar.IOC;
    9. using Sqlsugar.Business.Models;
    10. using Microsoft.Extensions.DependencyInjection;
    11. namespace MySqlsugar.Common
    12. {
    13. public static class SqlsugarSetup
    14. {
    15. public static void AddSqlsugarSetup()
    16. {
    17. List connectionConfigs = AppSettings.App(new string[] { "ConnectionConfigs" });
    18. //sqlsugar注册
    19. SugarIocServices.AddSqlSugar(connectionConfigs);
    20. //多租户日志打印设置/全局过滤器
    21. SugarIocServices.ConfigurationSugar(db =>
    22. {
    23. connectionConfigs.ForEach(item =>
    24. {
    25. SetQueryFilter(db.GetConnection(item.ConfigId));
    26. SetLog(db,item.ConfigId);
    27. });
    28. });
    29. }
    30. //日志
    31. private static void SetLog(SqlSugarClient db,string configid)
    32. {
    33. db.GetConnection(configid).Aop.OnLogExecuting = (sql, para) => {
    34. //var param = para.Select(it => it.Value).ToArray();
    35. string sqlQuery=UtilMethods.GetSqlString(DbType.SqlServer, sql, para);
    36. Console.WriteLine(sqlQuery);
    37. Console.WriteLine();
    38. };
    39. }
    40. ///
    41. /// 添加全局过滤器
    42. ///
    43. ///
    44. private static void SetQueryFilter(SqlSugarProvider provider)
    45. {
    46. //添加全局过滤器
    47. var files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "Sqlsugar.Business.dll");
    48. if (files.Length > 0)
    49. {
    50. Type[] types = Assembly.LoadFrom(files[0]).GetTypes().Where(it => it.BaseType == typeof(BaseEntity)).ToArray();
    51. foreach (var entityType in types)
    52. {
    53. var lambda = System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(
    54. new[] { Expression.Parameter(entityType, "it") },
    55. typeof(bool), $"{nameof(BaseEntity.IsDeleted)} == @0",
    56. false);
    57. provider.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda, true)); //将Lambda传入过滤器
    58. }
    59. }
    60. }
    61. }
    62. }

    Startup.cs中

     8.仓储注入

     Common中创建ConfigRepository.cs

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Threading.Tasks;
    5. using Microsoft.Extensions.DependencyInjection;
    6. using Sqlsugar.Business.Repository;
    7. namespace MySqlsugar.Common
    8. {
    9. ///
    10. /// 仓储注入
    11. ///
    12. public static class ConfigRepository
    13. {
    14. public static void ConfigureServices(IServiceCollection services)
    15. {
    16. services.AddScoped();
    17. services.AddScoped();
    18. }
    19. }
    20. }

    Startup.cs中

    9.Controller创建

    分别创建用户和图书两个接口文件

     10.启动接口,验证数据连接及数据表的创建

    接口启动分别调用用户和图书接口

     

     

    接口调用完成,会自动创建相关数据库及数据表

  • 相关阅读:
    玩一玩Spring容器
    CoppeliaSim机器人模拟器与Matlab Simulink环境
    element-UI 列表渲染图片,后台回传Base64
    ASP.NET Core - 选项系统之源码介绍
    【Redis】# 常见报错Unsatisfied dependency、设置密码、主从配置
    在Oracle中创建DBLINK
    uboot源码分析(基于S5PV210)之uboot的命令体系与环境变量
    cdn与云服务器有什么区别
    代码随想录-029-541.反转字符串II
    美创科技获通信网络安全服务能力评定(应急响应一级)认证!
  • 原文地址:https://blog.csdn.net/liwan09/article/details/126124716