暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

.net 简单的数据库操作框架

怀念和想念 2025-04-14
143

https://www.cnblogs.com/sunkaixuan/p/14701585.html

介绍

SqlSugar是一款 老牌 .NET数据库操作框架,由果糖大数据科技团队维护和更新 ,Github star数仅次于EF 和 Dapper

优点: 简单易用、功能齐全、高性能、轻量级、服务齐全、有专业技术支持一天18小时服务

支持数据库:MySql、SqlServer、Sqlite、Oracle 、 postgresql、达梦、人大金仓

 

框架新功能

最新稳定版本5.0.2.8 ,发布后1个月时间NUGET下载量达到5000的版本,用户使用也相当满意

而在稳定版本的基础上又布了5.0.2.9版本

加入3大新功能

1. 配置查询 

解决了大量字典表和简单就为取一个name 就要写联表的问题,让单表查询解决一切

2.多租户+仓储+自动分配

3.行转列

 

1、配置查询

解决了大量字典表和简单就为取一个name 就要写联表的问题,让单表查询解决一切

字典表我相信大家都全用到,他们可以方便的存储性别、学历、岗位等 一串数据 并进行TypeId进行区分

1.1 创建测试数据

创建一个字典实体

1

2

3

4

5

6

public class DataDictionary

{

    public string Code { getset; }

    public string Name { getset; }

    public string Type { getset; }

}

创建字典表并向里面插入测试数据  

1

2

3

4

5

6

7

8

9

10

11

var db = GetInstance();

            List<DataDictionary> datas = new List<DataDictionary>();

            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<DataDictionary>();//这样就能根据实体建表了

            db.Insertable(datas).ExecuteCommand();//这样就能把数据插进数据库了<br>

在建一个Person表  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class Person

{

    //数据库字段

    [SqlSugar.SugarColumn(IsPrimaryKey =true,IsIdentity =true)]

    public int Id { getset; }

    public string Name { getset; }

    public int SexId { getset; }

    public int CityId { getset; }

    public int ProvinceId { getset; }

 

    //非数据库字段

    [SqlSugar.SugarColumn(IsIgnore =true)]

    public string SexName { getset; }

    [SqlSugar.SugarColumn(IsIgnore = true)]

    public string CityName { getset; }

    [SqlSugar.SugarColumn(IsIgnore = true)]

    public string ProviceName { getset; }

} 

1.2 传统字典联表实现缺点

如果我们要将Person中的非数据字典查询出来那么我们就需要写有2种实现方式

1.连表或者子查询 (缺点 写起来很浪费时间)

2.将字典存到内存,通过内存赋值 (缺点 字典表超过1000条以上性能很差 ,并且不能排序,或者LIKE)

下面介绍通过SqlSugar的配置查询解决上2面个难题

 

1.3 配置表简化字典联表

配置字典表

 

1

2

3

4

5

6

7

8

9

if (!db.ConfigQuery.Any())

   {

                var types= db.Queryable<DataDictionary>().Select(it => it.Type).Distinct().ToList();

                foreach (var type in types)

                {

                    db.ConfigQuery.SetTable<DataDictionary>(it => it.Code, it => it.Name, type, it => it.Type == type);

                }

                //如果其中Code都是唯一值可以按 1.4中的用法使用循环都不要

}

 

配置完我们查询就会很方便了

1

2

3

4

5

6

7

8

9

   var res=db.Queryable<Person>().Select(it => new Person()

   {

                 Id=it.Id.SelectAll(),

                 SexName=it.SexId.GetConfigValue<DataDictionary>("sex"),

                 ProvinceName = it.ProvinceId.GetConfigValue<DataDictionary>("province"),

                 CityName = it.CityId.GetConfigValue<DataDictionary>("city"),

   }).ToList();

 

//也支持支持写在Where或者Orderby 

1.4 简单联表查询也可以配置

1

2

3

4

5

6

db.ConfigQuery.SetTable<Order>(it => it.Id, it => it.Name);//配置Order<br>

var list3 = db.Queryable<OrderItem>().Select(it => new OrderItem

{

        ItemId = it.ItemId.SelectAll(),

        OrderName = it.OrderId.GetConfigValue<Order>() //查询的时候直接用

}).ToList();

 总结:配置表查询的方式可以大大降低重复联表问题,并且配置好后基本就不要写JOIN了 

  

2、多租户+仓储+自动分配

SqlSugar多租户是通过ConfigId进行识别连接哪个库,新版本添加了实体配置ConfigId

1

2

3

4

5

6

7

8

9

10

11

[TenantAttribute("1")]

  public class C1Table

  {

     public string Id { getset; }

  }

 

  [TenantAttribute("2")]

  public class C2Table

  {

      public string Id { getset; }

  }

  

下面我们仓储就可以通过实体配置自动识别是连接哪个库   

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

public class Repository<T> : SimpleClient<T> where T : classnew()

    {

        public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null

        {

            if (context == null)

            {

                var db = new SqlSugarClient(new List<ConnectionConfig> {

                                                    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<TenantAttribute>().configId;

                db.ChangeDatabase(configId);

            }

        }

 

        /// <summary>

        /// 扩展方法,自带方法不能满足的时候可以添加新方法

        /// </summary>

        /// <returns></returns>

        public List<T> CommQuery(string sql)

        {

            //base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作

            return base.Context.Queryable<T>().Where(sql).ToList();

        }

 

    }

  

新版本还添加了切换仓储功能

1

2

3

4

5

6

7

8

9

10

11

12

public class C1Service : Repository<C1Table>

{

    public void Test()

    {

        base.AsTenant().BeginTran();

 

        base.GetList(); //调用内部仓储方法

        base.ChangeRepository<Repository<C2Table>>().GetList();//调用外部仓储

 

        base.AsTenant().CommitTran();

    }

}

  

 3、行列互转功能 

第一个参数 列名、第二个参数 头行名、第三个参数 值

1

2

3

4

5

6

7

var test06 = db.Queryable<Order>()

                   .ToPivotTable(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));//返回Datatable

 

 var test07 = db.Queryable<Order>()

            .ToPivotList(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));//返回List<dynamic><br>

var test08 = db.Queryable<Order>()

            .ToPivotJson(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));//返回Json

 

.NET数据库框架源码  

官网地址:  https://www.donet5.com/Home/Doc

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论