SqlSugar梳理


SqlSugar梳理

一、SqlSugar介紹:

sqlsugar是一款非常輕量級並且特別強大的ORM,支持常見的關系型數據庫(Oracle , sqlserver , MySQL等)

二、SqlSugar常用方法介紹:

1. 基礎方法:

public static void Show()
        {
            SqlSugarClient sqlSugarClient = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                ConnectionString = "Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB;Persist Security Info=True;User ID=sa;Password=sa123",
                IsAutoCloseConnection = true
            });

            //獲取執行的sql
            sqlSugarClient.Aop.OnLogExecuting = (sql, pra) =>
            {
                Console.WriteLine("********************************************");
                Console.WriteLine($"Sql語句:{sql}");
            };


            //新增一條數據
            sqlSugarClient.Insertable<Commodity>(new Commodity()
            {
                CategoryId = 123,
                ImageUrl = "ImageUrl",
                Price = 34567,
                ProductId = 2345,
                Title = "測試數據",
                Url = "Url"
            }).ExecuteCommand();

            List<Commodity> list = sqlSugarClient.Queryable<Commodity>().ToList(); 
            Commodity commodity = sqlSugarClient.Queryable<Commodity>().First();
            commodity.ImageUrl = commodity.ImageUrl + "Test";
            sqlSugarClient.Updateable<Commodity>(commodity).ExecuteCommand(); 
            sqlSugarClient.Deleteable<Commodity>(commodity).ExecuteCommand();
        }

基礎方法2:讀寫分離,經過測試,從庫數據會有1.5秒左右的延遲

public static void Show()
        {

            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB;Persist Security Info=True;User ID=sa;Password=sa123",//主庫
                DbType = DbType.SqlServer,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
                //從庫
                SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString="Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB_001;Persist Security Info=True;User ID=sa;Password=sa123" } ,
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString="Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB_002;Persist Security Info=True;User ID=sa;Password=sa123" },
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString="Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB_003;Persist Security Info=True;User ID=sa;Password=sa123" }
                }
            });

            //db.Aop.OnLogExecuting = (sql, pra) =>
            //{
            //    Console.WriteLine("*********************************");
            //    Console.WriteLine($"Sql語句:{sql}");
            //};


            /////新增---必然是要操作主庫
            //db.Insertable<Commodity>(new Commodity()
            //{
            //    CategoryId = 123,
            //    ImageUrl = "測試數據讀寫分離",
            //    Price = 34567,
            //    ProductId = 2345,
            //    Title = "測試數據讀寫分離",
            //    Url = "測試數據讀寫分離"
            //}).ExecuteCommand();

            //db.Insertable<Commodity>(new Commodity()
            //{
            //    CategoryId = 123,
            //    ImageUrl = "測試數據讀寫分離",
            //    Price = 34567,
            //    ProductId = 2345,
            //    Title = "測試數據讀寫分離",
            //    Url = "測試數據讀寫分離"
            //}).ExecuteCommand();

            ///查詢---應該到從庫中去查詢---如果證明是在從庫中查詢的呢?---確實是到從庫中去查詢的 
            //for (int i = 0; i < 20; i++)
            //{
            //    Commodity commodity = db.Queryable<Commodity>().First(c => c.Id == 10011);
            //    Console.WriteLine(commodity.Title);
            //}

            //中間有延遲嗎?---有延遲的; 需要大家理解
            {
                db.Insertable<Commodity>(new Commodity()
                {
                    CategoryId = 123,
                    ImageUrl = "測試延遲的數據-1",
                    Price = 34567,
                    ProductId = 2345,
                    Title = "測試延遲的數據-1",
                    Url = "測試延遲的數據-1"
                }).ExecuteCommand();
                bool isGoOn = true;
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                while (isGoOn)
                {
                    db.Ado.IsDisableMasterSlaveSeparation = true;  //可以走主庫

                    Commodity commodity = db.Queryable<Commodity>().OrderBy(c => c.Id, OrderByType.Desc).First();
                    if (commodity.Title == "測試延遲的數據-1")
                    {
                        Console.WriteLine("已經同步了");
                        isGoOn = false;
                        stopwatch.Stop();
                        Console.WriteLine($"延遲時間:{stopwatch.ElapsedMilliseconds.ToString()}");
                    }
                    else
                    {
                        Console.WriteLine("還沒有同步");
                    }
                }
            }
            //主從賦值有延遲:
            //1.忍了
            //2.還是基於主庫去查詢一下

            //db.Ado.IsDisableMasterSlaveSeparation = true;  //可以走主庫

        }

 

三、.net core項目中使用該框架

1. ConfigureServices中配置如下:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<ICommodityService, CommodityService>();

            #region SqlSugar
            
            services.AddTransient<ISqlSugarClient>(option =>
            {
                SqlSugarClient client = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = "Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB;Persist Security Info=True;User ID=sa;Password=sa123",
                    DbType = DbType.SqlServer,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    //配置從庫
                    SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString="Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB_001;Persist Security Info=True;User ID=sa;Password=sa123" } ,
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString="Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB_002;Persist Security Info=True;User ID=sa;Password=sa123" },
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString="Data Source=DESKTOP-T2D6ILD;Initial Catalog=SqlSugarCustomerDB_003;Persist Security Info=True;User ID=sa;Password=sa123" },

                }
                });

                client.Aop.OnLogExecuting = (sql, par) =>
                {
                    Console.WriteLine($"Sql語句{sql}");
                };

                return client;

            });
            #endregion
            services.AddControllersWithViews();
        }

2. Service層中使用:新建一個具有公共方法的 BaserService類

public class BaserService : IBaserService
    {
        protected ISqlSugarClient _Client;

        public BaserService(ISqlSugarClient client)
        {
            this._Client = client;
        }

        public bool Add<T>(T t) where T : class, new()
        {
            return _Client.Insertable<T>(t).ExecuteCommand() > 0;
        }

        public bool Delete<T>(T t) where T : class, new()
        {
            return _Client.Deleteable<T>(t).ExecuteCommand() > 0;
        }

        public List<T> Query<T>() where T : class, new()
        {
            return _Client.Queryable<T>().ToList();
        }

        public bool Update<T>(T t) where T : class, new()
        {
            return _Client.Updateable<T>(t).ExecuteCommand() > 0;
        }
    }

3 實現

 public interface IBaserService
    {
        public bool Add<T>(T t) where T : class, new();

        public List<T> Query<T>() where T : class, new();

        public bool Update<T>(T t) where T : class, new();

        public bool Delete<T>(T t) where T : class, new();

    }

4. 其他service中的類需要繼承上面的公共方法

public class CommodityService : BaserService, ICommodityService
    {
        public CommodityService(ISqlSugarClient client) : base(client)
        {

        }
     //這個是分頁的方法
        public List<Commodity> PageCommodityList(out int totalCount, string searchString1, string searchString2, int pageIndex = 1, int pageSize = 10)
        {
             
            //Expressionable<Commodity> expressionable = Expressionable.Create<Commodity>();
            //expressionable = expressionable.AndIF(!string.IsNullOrWhiteSpace(searchString1), c => c.Title.Contains(searchString1));
            //expressionable = expressionable.AndIF(!string.IsNullOrWhiteSpace(searchString2), c => c.Title.Contains(searchString2));
            //Expression<Func<Commodity, bool>> expression = expressionable.ToExpression();

            int totalNum = 0;
            //List<Commodity> list = _Client.Queryable<Commodity>().Where(expression)
            List<Commodity> list = _Client.Queryable<Commodity>()
                .WhereIF(!string.IsNullOrWhiteSpace(searchString1), c => c.Title.Contains(searchString1))
                .WhereIF(!string.IsNullOrWhiteSpace(searchString2), c => c.Title.Contains(searchString2))
                 .OrderBy(c => c.Id, OrderByType.Asc)
                  .ToPageList(pageIndex, pageSize, ref totalNum);
            totalCount = totalNum;
            return list;
        }
    }

5. 接口:

 public interface ICommodityService: IBaserService
    {
        //public void Add();

        //public void Query();


        //public void Update();


        //public void Delete();

        public List<Commodity> PageCommodityList(out int totalCount,string searchString1, string searchString2, int pageIndex = 1, int pageSize = 10);
    }

 

更新完成!謝謝學習,共同進步

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM