ORM之SqlSugar


前言:本文將從SqlSugar的介紹、SqlSugar的優點、SqlSugar的具體使用對該ORM框架做簡單的學習記錄

SqlSugar的介紹

         SqlSugar ORM,NET 4.+ & .NET CORE 高性能輕量級ORM框架,眾多.NET框架中最容易使用的數據庫訪問技術。

SqlSugar的優點

  • 高性能 。不誇張的說,去掉Sql在數據庫執行的時間,SqlSugar是EF數倍性能,另外在批量操作和一對多查詢上也有不錯的SQL優化
  • 高擴展性 。支持自定義拉姆達函數解析、擴展數據類型、支持自定義實體特性,外部緩存等
  • 穩定性和技術支持。 雖然不是官方ORM, 但在穩定性上也是有着數年用戶積累,如果遇到問題可以在GITHUB提出來,會根據緊急度定期解決
  • 功能全面。雖然SqlSugar小巧可功能並不遜色於EF框架
  • 創新、持續更新 ,向下兼容

SqlSugar的使用

項目依賴項中添加SQLSugarCore(如果用的是.NET Freamwork 選擇 Sqlsugar即可),這里項目用的是.NET Core 3.1 所以選擇安裝 SqlSugarCore

我在項目中新增了一個SqlSugarHelper的幫助類,先來看看數據庫連接配置:

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Helper.ORM
{
    public class SqlSugarHelper
    {
        SqlSugarClient _client = new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = "",//數據庫連接字符串
            DbType = DbType.SqlServer,//設置數據庫類型
            IsAutoCloseConnection = true,//自動釋放數據庫,如果存在事務,在事務結束后釋放
            InitKeyType = InitKeyType.Attribute //從實體特性中讀取主鍵自增列信息
        });
    }
}

      連接配置中有個DbType,具體枚舉類如下:

namespace SqlSugar
{
    public enum DbType
    {
        MySql = 0,
        SqlServer = 1,
        Sqlite = 2,
        Oracle = 3,
        PostgreSQL = 4,
        Dm = 5,
        Kdbndp = 6
    }
}

      可以看出,目前SqlSugar 支持的數據庫有:MySql、SqlServer、Sqlite、Oracle、PostgreSQL、Dm、Ddbndp,基本包含了主流常用的數據庫類型

然后從CRUD對SqlSugar的用法做個介紹:

  • C-Create 創建/新增:

示例如下:

            //1:新增返回影響行數
            var data = new Student() { Name = "zhangsan", ClassId = 101, Sex = "", Age = 22 };
            int count = _client.Insertable(data).ExecuteCommand();

            //2:返回自增列
            int newId = _client.Insertable(data).ExecuteReturnIdentity();

            //3:插入返回新增的實體
            var newModel = _client.Insertable(data).ExecuteReturnEntity();

            //4:只插入部分列
            count = _client.Insertable(data)
                 .InsertColumns(t => new { t.Name, t.ClassId })
                 .ExecuteReturnIdentity();

            //5:忽略部分列
            count = _client.Insertable(data)
                   .IgnoreColumns(t => new { t.Age })
                   .ExecuteReturnIdentity();
            //6:根據條件指定不插入列
            count = _client.Insertable(data)
                   .IgnoreColumns(t => t.Age < 18)
                   .ExecuteReturnIdentity();

            //7:插入使用鎖
            count = _client.Insertable(data)
                   .With(SqlWith.UpdLock)
                   .ExecuteReturnIdentity();

            //8:批量插入(性能很快不用操心)
            var list = new List<Student>();
            list.Add(new Student() { Name = "zhangsan", ClassId = 101, Sex = "", Age = 22 });
            list.Add(new Student() { Name = "lisi", ClassId = 101, Sex = "", Age = 23 });
            _client.Insertable(list).ExecuteCommand();
            _client.Insertable(list.ToArray()).ExecuteCommand();
  • R-Retrieve 檢索/查詢:

 部分示例如下:

            //1:查詢所有數據
            var list = _client.Queryable<Student>().ToList();

            //2:根據主鍵查詢單條數據
            var model = _client.Queryable<Student>().InSingle(1);

            //3:根據條件查詢
            var list2 = _client.Queryable<Student>().Where(it => it.Sex == "").ToList();

            //4:分頁查詢
            var total = 0;
            var getPage = _client.Queryable<Student>().Where(it => it.Age > 18).ToPageList(1, 2, ref total);//分頁查詢

            //5:兩張表聯合查詢(其中Student為學生表、Class為班級表;JoinType為連接方式(Inner,Left,Right)、第二個為兩張表的關聯字段)
            //5.1 方式一
            var query = _client.Queryable<Student, Class>((a, b) => new object[] {
                JoinType.Left,
                a.ClassId==b.Id
            });

            //5.2:方式二 (未指定連接方式默認Inner)
            query = _client.Queryable(_client.Queryable<Student>(), _client.Queryable<Class>(), (a, b) => a.ClassId == b.Id);

            //5.3:方式三 (指定連接方式)
            query = _client.Queryable(_client.Queryable<Student>(), _client.Queryable<Class>(), JoinType.Left, (a, b) => a.ClassId == b.Id);
  • U-Update:更新:

示例如下:

            var data = new Student() { Id = 1, Name = "zhangsan", ClassId = 101, Sex = "", Age = 22 };
            var list = new List<Student>();

            //1:根據實體更新(主鍵要有值,主鍵是更新條件)
            var count = _client.Updateable(data).ExecuteCommand();

            //2:傳入對象根據條件更新
            count = _client.Updateable(data)
                   .WhereColumns(t => new { t.Id })
                   .ExecuteCommand();

            //3:更新部分列
            count = _client.Updateable(data)
                   .UpdateColumns(x => new { x.Name, x.Age, x.ClassId })
                   .WhereColumns(t => new { t.Id })
                   .ExecuteCommand();

            //4:批量更新
            count = _client.Updateable(list).ExecuteCommand();
  • D-Delete:刪除:

示例如下:

            var data = new Student() { Id = 1, Name = "zhangsan", ClassId = 101, Sex = "", Age = 22 };
            var list = new List<Student>();

            //1:根據實體刪除
            var count = _client.Deleteable(data).ExecuteCommand();

            //2:根據主鍵刪除
            count = _client.Deleteable<Student>(1).ExecuteCommand();

            //3:根據條件刪除
            count = _client.Deleteable<Student>()
                   .Where(t => t.Age < 19)
                   .ExecuteCommand();

            //4:批量實體刪除
            count = _client.Deleteable(list).ExecuteCommand();

            //5:批量根據主鍵刪除
            List<int> ids = new List<int>();
            count = _client.Deleteable<Student>(ids).ExecuteCommand();

 再來看看SqlSugar的其他用法:

  • 實體類用法:
     //如果實體類名稱和表名不一致可以加上SugarTable特性指定表名
    [SugarTable("Student")]
    public class StudentModel
    {
        //指定主鍵和自增列,當然數據庫中也要設置主鍵和自增列才會有效
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }
        public string Name { get; set; }
    }
  • 根據實體類創建對象:
    _client.CodeFirst.SetStringDefaultLength(200/*設置varchar默認長度為200*/).InitTables(typeof(StudentModel));//執行完數據庫就有這個表了
  • 原生SQL執行:
            string sql = "select * from student";
            List<SugarParameter> pms = new List<SugarParameter>();
            pms.Add(new SugarParameter("id", 1));

            //1:寫SQL,分頁、查詢條件用表達式
            _client.SqlQueryable<Student>("select * from student").Where(it => it.Id ==1).ToPageList(1, 2);

            //2:純SQL
            _client.Ado.ExecuteCommand(sql, pms);

            //3:執行存儲過程
            _client.Ado.UseStoredProcedure();

            var count = _client.Ado.UseStoredProcedure().ExecuteCommand("存儲過程名稱", pms);
            var dt = _client.Ado.UseStoredProcedure().GetDataTable("存儲過程名稱", pms);
  • SqlSugar 常用函數:
public class SqlFunc
{
    public static TResult AggregateAvg<TResult>(TResult thisValue);//針對這個列進行取平均數統計
    public static int AggregateCount<TResult>(TResult thisValue);// 統計這個列數量 等價於 SQL里的 count(x)
    public static int AggregateDistinctCount<TResult>(TResult thisValue);/ 返回去重之后的數量
    public static TResult AggregateMax<TResult>(TResult thisValue);//返回最大值
    public static TResult AggregateMin<TResult>(TResult thisValue);// 返回最小值
    public static TResult AggregateSum<TResult>(TResult thisValue);// 返回總和
    public static bool Between(object value, object start, object end);// 判斷列的值是否在兩個值之間
    public static int CharIndex(string findChar, string searchValue);// SQL 的charindex
    public static bool Contains(string thisValue, string parameterValue);// 是否包含
    public static bool ContainsArray<T>(T[] thisValue, object InField);// 數組是否包含
    public static bool ContainsArray<T>(List<T> thisValue, object InField);//列表蘇菲包含
    public static bool ContainsArrayUseSqlParameters<T>(List<T> thisValue, object InField);//
    public static bool ContainsArrayUseSqlParameters<T>(T[] thisValue, object InField);//
    public static DateTime DateAdd(DateTime date, int addValue, DateType dataType);// 時間添加
    public static DateTime DateAdd(DateTime date, int addValue);// 日期添加
    public static bool DateIsSame(DateTime date1, DateTime date2);// 時間是否相同
    public static bool DateIsSame(DateTime? date1, DateTime? date2);//時間是否相同
    public static bool DateIsSame(DateTime date1, DateTime date2, DateType dataType);//時間是否相同,根據DateType判斷
    public static int DateValue(DateTime date, DateType dataType);// 根據dateType, 返回具體的時間值
    public static bool EndsWith(string thisValue, string parameterValue);//字符串是否以某些值結尾
    public static bool Equals(object thisValue, object parameterValue);//是否相等
    public static DateTime GetDate();//返回當前數據庫時間
    public static string GetRandom();//
    public static TResult GetSelfAndAutoFill<TResult>(TResult value);//
    public static bool HasNumber(object thisValue);//返回是否大於0,且不能為Null
    public static bool HasValue(object thisValue);// 是否有值,且不為Null
    public static CaseThen IF(bool condition);// sql 里的if判斷
    public static TResult IIF<TResult>(bool Expression, TResult thenValue, TResult elseValue);// case when
    public static TResult IsNull<TResult>(TResult thisValue, TResult ifNullValue);// sql 里的 IsNull
    public static bool IsNullOrEmpty(object thisValue);//判斷是否是Null或者空
    public static int Length(object value);//取長度
    public static TResult MappingColumn<TResult>(TResult oldColumnName, string newColumnName);// 列名映射
    public static string MergeString(string value1, string value2);
    public static string MergeString(string value1, string value2, string value3, string value4);
    public static string MergeString(string value1, string value2, string value3, string value4, string value5);
    public static string MergeString(string value1, string value2, string value3, string value4, string value5, string value6);
    public static string MergeString(string value1, string value2, string value3);
    public static string MergeString(string value1, string value2, string value3, string value4, string value5, string value6, string value7);
    public static string Replace(object value, string oldChar, string newChar);// 替換
    public static bool StartsWith(string thisValue, string parameterValue);
    public static Subqueryable<T> Subqueryable<T>() where T : class, new();
    public static string Substring(object value, int index, int length);// 獲取子串
    public static bool ToBool(object value);//類型轉換
    public static DateTime ToDate(object value);// 類型轉換
    public static decimal ToDecimal(object value);// 類型轉換
    public static double ToDouble(object value);// 類型轉換
    public static Guid ToGuid(object value);// 類型轉換
    public static int ToInt32(object value);// 類型轉換
    public static long ToInt64(object value);// 類型轉換
    public static string ToLower(object thisValue);// 類型轉換
    public static string ToString(object value);// 類型轉換
    public static TimeSpan ToTime(object value);// 類型轉換
    public static string ToUpper(object thisValue);// 類型轉換
    public static string Trim(object thisValue);// 去除首尾的空格
}

參考網址:查詢 - 查詢函數 - 《SqlSugar 4.0 文檔》 - 書棧網 · BookStack

SqlSugar官網:https://www.donet5.com/Doc/99999999999/1197

以上就是SqlSugar的一些簡單使用,其他復雜用法可以上官網學習,最后不得的不感慨一句,SqlSugar太強大了~

 


免責聲明!

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



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