本文共 4511 字,大约阅读时间需要 15 分钟。
SqlSugar 是一款经典的 .NET 数据库操作框架,由果糖大数据科技团队维护和持续更新。作为一款功能强大且性能优越的数据库操作工具,SqlSugar 在开发者社区获得了广泛的认可,其 GitHub star 数量仅次于 EF 和 Dapper。
SqlSugar 的最新稳定版本为 5.0.2.8,在发布后的一个月内在 NuGet 平台下载量达到 5000 次,用户反馈极其满意。随后又推出了 5.0.2.9 版本,基于稳定版本的基础上新增了 3 个核心功能:
SqlSugar 的配置查询功能通过预先定义字典表,实现了在单表查询中直接获取所需信息的需求。以下是使用配置查询功能的具体示例:
首先,创建一个字典实体类:
public class DataDictionary{ public string Code { get; set; } public string Name { get; set; } public string Type { get; set; }} 然后,通过 SqlSugar 初始化字典表并插入测试数据:
var db = GetInstance();var datas = new List();datas.Add(new DataDictionary() { Code = "1", Name = "男", Type = "sex" });datas.Add(new DataDictionary() { Code = "2", Name = "女", Type = "sex" });datas.Add(new DataDictionary() { Code = "1", Name = "南通市", Type = "city" });datas.Add(new DataDictionary() { Code = "2", Name = "苏州市", Type = "city" });datas.Add(new DataDictionary() { Code = "1", Name = "江苏省", Type = "province" });datas.Add(new DataDictionary() { Code = "2", Name = "湖南省", Type = "province" });db.CodeFirst.InitTables(datas);db.Insertable(datas).ExecuteCommand();
在传统的数据库设计中,字典表查询往往面临以下问题:
通过 SqlSugar 的配置查询功能,可以在单表查询中直接解决字典表问题。以下是具体实现步骤:
if (!db.ConfigQuery.Any()){ var types = db.Queryable () .Select(it => it.Type) .Distinct() .ToList(); foreach (var type in types) { db.ConfigQuery.SetTable( it => it.Code, it => it.Name, type, it => it.Type == type ); }} var res = db.Queryable() .Select(it => new Person() { Id = it.Id.SelectAll(), SexName = it.SexId.GetConfigValue("sex"), ProvinceName = it.ProvinceId.GetConfigValue("province"), CityName = it.CityId.GetConfigValue("city") }) .ToList();
通过配置查询功能,开发者可以显著降低重复联表查询的工作量,提升开发效率。
SqlSugar 的多租户功能通过 ConfigId 区分不同的数据库实例,支持动态切换数据库。以下是实现多租户的具体代码示例:
public class Repository: SimpleClient where T : class, new(){ public Repository(ISqlSugarClient context = null) : base(context) { if (context == null) { var db = new SqlSugarClient(new List () { new ConnectionConfig() { ConfigId = "1", DbType = SqlSugar.DbType.SqlServer, IsAutoCloseConnection = true, ConnectionString = Config.ConnectionString }, new ConnectionConfig() { ConfigId = "2", DbType = SqlSugar.DbType.SqlServer, IsAutoCloseConnection = true, ConnectionString = Config.ConnectionString2 } }); base.Context = db; var configId = typeof(T).GetCustomAttribute ().ConfigId; db.ChangeDatabase(configId); } } public List CommQuery(string sql) { return base.Context.Queryable () .Where(sql) .ToList(); }}
此外,新版本还增加了切换仓储功能,支持在同一个服务中切换不同的数据仓储。
SqlSugar 的行转列功能可以将数据以表格形式返回,支持多种数据格式。以下是使用行转列功能的示例:
var test06 = db.Queryable() .ToPivotTable(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));var test07 = db.Queryable () .ToPivotList(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));var test08 = db.Queryable () .ToPivotJson(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));
通过行转列功能,开发者可以方便地将数据转换为多种格式,提升数据处理效率。
SqlSugar 作为一款功能强大、性能优越的数据库操作框架,通过配置查询、多租户支持和行转列功能等创新功能,显著提升了开发者的工作效率。如果你正在寻找一款适合 .NET 开发的数据库操作框架,SqlSugar 可能是你的不二之选。
转载地址:http://shofz.baihongyu.com/