C# 數(shù)據(jù)操作系列 - 15 SqlSugar 增刪改查詳解

0. 前言

繼上一篇,以及上上篇,我們對SqlSugar有了一個大概的認(rèn)識,但是這并不完美,因?yàn)槟切┒际抢碚撝R,無法描述我們工程開發(fā)中實(shí)際情況。而這一篇,將帶領(lǐng)小伙伴們一起試著寫一個能在工程中使用的模板類。

1. 創(chuàng)建一個Client

SqlSugar在操作的時候需要一個Client,用來管理數(shù)據(jù)庫連接,并操作數(shù)據(jù)庫。所以我們寫一個DbContext用來創(chuàng)建Client:

public class DefaultContext
{
    public SqlSugarClient Client { get; }

    public DefaultContext(string connectionString, DbType dbType)
    {
        Client = new SqlSugarClient(new ConnectionConfig
        {
            ConnectionString = connectionString,//"Data Source=./demo.db",
            DbType = dbType,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });
        Client.CodeFirst.InitTables(typeof(Dept), typeof(Person), typeof(Employee));
        Client.Aop.OnLogExecuting = (sql, paramters) =>
        {
            Console.WriteLine(sql);
        };
    }

    public SimpleClient<T> CreateClient<T>() where T : class, new()
    {
        return Client.GetSimpleClient<T>();
    }
}

SqlSugar 提供了一個SimpleClient,這里面有很多可以直接拿來用的方法,而且這個是一個泛型類。也就是說我們可以使用它對單個實(shí)體類進(jìn)行操作,這在開發(fā)中很重要。

2. 插入數(shù)據(jù)

對于一個程序而言,數(shù)據(jù)就像是血液一樣重要。對于ORM框架,插入是一切來源的基礎(chǔ)。所以我們先來看看SqlSugar的插入是怎樣的吧:

2.1 簡單的插入模式

public bool Insert(T insertObj);
public bool InsertRange(T[] insertObjs);
public bool InsertRange(List<T> insertObjs);

這是SqlSugar在SimpleClient里提供的兩個默認(rèn)插入方法,一個是插入單個實(shí)體對象,一個是插入一組對象。

默認(rèn)情況下,SqlSugar插入并不會將主鍵返回給數(shù)據(jù)。如果后續(xù)操作需要當(dāng)前數(shù)據(jù)的主鍵,則可以調(diào)用另外一個方法:

public int InsertReturnIdentity(T insertObj);

通過這個方法可以獲取一個默認(rèn)的int類型主鍵值。

2.2 高級玩法

SqlSugar還有一種插入模式,通過AsInsertable返回一個 IInsertable泛型接口:

public IInsertable<T> AsInsertable(T insertObj);
public IInsertable<T> AsInsertable(T[] insertObjs);
public IInsertable<T> AsInsertable(List<T> insertObjs);

這種模式與SimpleClient的普通插入模式不同,它并不會直接執(zhí)行插入動作,需要手動調(diào)用并執(zhí)行插入動作:

int ExecuteCommand();

執(zhí)行動作,然后返回受影響的行數(shù)。

bool ExecuteCommandIdentityIntoEntity();

執(zhí)行動作,然后將主鍵插入實(shí)體對象,返回插入結(jié)果。執(zhí)行完成后,主鍵數(shù)據(jù)保存到實(shí)體示例中。

long ExecuteReturnBigIdentity();
int ExecuteReturnIdentity();

執(zhí)行動作,然后返回主鍵值,不會更新實(shí)體。

有一點(diǎn)值得特別注意:

所有會返回主鍵的插入都只針對單個數(shù)據(jù),如果一次插入多個數(shù)據(jù),并不會返回主鍵信息也無法將主鍵信息更新入實(shí)體中

以上都是全列插入,SqlSugar還提供了只插入部分列和忽略某些列兩種模式:

IInsertable<T> InsertColumns(Expression<Func<T, object>> columns);// 滿足條件的插入,其他列則不插入
IInsertable<T> InsertColumns(params string[] columns);//插入指定列名
IInsertable<T> IgnoreColumns(Expression<Func<T, object>> columns);// 忽略滿足條件的列,插入其他列
IInsertable<T> IgnoreColumns(params string[] columns);// 忽略這幾個列
IInsertable<T> IgnoreColumns(bool ignoreNullColumn, bool isOffIdentity = false);//指定是否忽略Null列,并是否強(qiáng)制插入主鍵

3. 更新或插入

介紹完插入,那么來介紹一下更新。正所謂,沒有更新數(shù)據(jù)就是一灘死水,有了更新數(shù)據(jù)才有了變化。所以,就讓我們來看看如何優(yōu)雅的更新數(shù)據(jù)吧:

3.1 簡單模式

先來兩個最簡單的:

public bool Update(T updateObj);
public bool UpdateRange(T[] updateObjs);
public bool UpdateRange(List<T> updateObjs);

傳入實(shí)體,直接更新到數(shù)據(jù)庫中,需要注意的是這種更新模式只需要保證主鍵有值,且與之對應(yīng)即可。

public bool Update(Expression<Func<T, T>> columns, Expression<Func<T, bool>> whereExpression);

這是另一種條件更新,會更新滿足whereExpression的所有元素,更新示例:

personClient.Update(p=>new Person
{
    Age = 1
}, p=>p.Id == 1);

columns需要返回一個要更新的對象的屬性列,也就是在columns中設(shè)置需要更新的內(nèi)容。

3.2 高級模式

同樣,通過AsUpdateable開啟高級模式:

public IUpdateable<T> AsUpdateable(T[] updateObjs);
public IUpdateable<T> AsUpdateable(T updateObj);
public IUpdateable<T> AsUpdateable(List<T> updateObjs);

然后可以針對這些今天更多的操作:

int ExecuteCommand();

返回命令執(zhí)行影響的行數(shù)

bool ExecuteCommandHasChange();

返回是否有變化,也就是影響行數(shù)是否大于0。

  • 只更新某些列:
IUpdateable<T> SetColumns(Expression<Func<T, bool>> columns);

更新示例:

personClient.AsUpdateable(d).SetColumns(t=>t.Age ==2).ExecuteCommand();

傳入一個lambda表達(dá)式,使數(shù)據(jù)滿足lambda表達(dá)式。要求lambda表達(dá)式只能用 == 來判斷列是否等于某個值。

IUpdateable<T> SetColumns(Expression<Func<T, T>> columns);
IUpdateable<T> UpdateColumns(params string[] columns);
IUpdateable<T> UpdateColumns(Expression<Func<T, object>> columns);

傳入要更新的實(shí)際列名。其中 object 用來接一個匿名對象,其中屬性名字就是要更新的值。

  • 不更新某些列
IUpdateable<T> IgnoreColumns(params string[] columns);// 忽略傳入的列名
IUpdateable<T> IgnoreColumns(Expression<Func<T, object>> columns);// 用匿名對象表示要忽略的列名
IUpdateable<T> IgnoreColumns(bool ignoreAllNullColumns, bool isOffIdentity = false, bool ignoreAllDefaultValue = false);// 設(shè)置是否忽略Null列,是否強(qiáng)制更新主鍵,是否忽略所有默認(rèn)值列
  • 條件更新
IUpdateable<T> Where(Expression<Func<T, bool>> expression);
IUpdateable<T> Where(string fieldName, string conditionalType, object fieldValue);
IUpdateable<T> Where(string whereSql, object parameters = null);
IUpdateable<T> WhereColumns(Expression<Func<T, object>> columns);
IUpdateable<T> WhereColumns(string columnName);
IUpdateable<T> WhereColumns(string[] columnNames);

來,簡單猜一猜這幾個是什么意思呢?

可以說很簡單明了的幾種條件設(shè)置模式,lambda表示篩選更新數(shù)據(jù),字段值判斷條件更新。

其中 conditionType的值,推薦使用 ConditionalType枚舉的值。

3.3 更新或插入

在實(shí)際開發(fā)中可能會遇到插入或更新是走的一個方法,所以我們就要尋找一個可以直接更新或插入的方法。SqlSugar為此提供了解決方案:

ISaveable<T> Saveable<T>(T saveObject) where T : class, new();
ISaveable<T> Saveable<T>(List<T> saveObjects) where T : class, new();

不過這個方法是在SugarClient里,我們可以通過:

public ISqlSugarClient AsSugarClient();

在SimpleClient中獲得 與之關(guān)聯(lián)的SugarClient對象。

關(guān)于更新或插入判斷標(biāo)準(zhǔn)是,主鍵是否有值。如果主鍵有值且在數(shù)據(jù)庫中存在該條記錄,則執(zhí)行更新,否則執(zhí)行插入。

4. 刪除

刪除在實(shí)際開發(fā)過程中是一個非常重要的功能點(diǎn),所以如何快速有效的刪除數(shù)據(jù)也是一件很重要的事。那么,就來看看如何執(zhí)行刪除吧:

public bool Delete(Expression<Func<T, bool>> whereExpression);
public bool Delete(T deleteObj);
public bool DeleteById([Dynamic] dynamic id);
public bool DeleteByIds([Dynamic(new[] { false, true })] dynamic[] ids);

刪除沒有其他需要注意的地方,第一個是條件刪除,所有滿足條件的都要刪除。第二個刪除單個對象,后面兩個根據(jù)主鍵刪除對象。

悄悄吐槽一下,主鍵的地方用object會比較好一點(diǎn),因?yàn)閯討B(tài)對象會增加一次裝箱拆箱的過程。

當(dāng)然了,刪除也有AsDeleteable方法。IDeleteable接口特別提供了根據(jù)sql語句刪除的方法,除此之外沒有別的需要注意的地方了。

5. 查詢

一個好的ORM框架,至少五分功力在查詢上,如何更快更準(zhǔn)的查詢成為了現(xiàn)在開發(fā)對ORM框架的要求。同時簡單易用更是程序員對ORM的期望。

那么我們來看看SqlSugar在查詢上的功力吧:

public bool IsAny(Expression<Func<T, bool>> whereExpression);// 查詢是否存在符合條件的數(shù)據(jù)
public int Count(Expression<Func<T, bool>> whereExpression);// 獲取滿足條件的數(shù)量
public T GetById([Dynamic] dynamic id);//根據(jù)主鍵獲取一個實(shí)例
public bool IsAny(Expression<Func<T, bool>> whereExpression);//返回滿足條件的一個對象
public List<T> GetList();// 以List的形式返回所有數(shù)據(jù)
public List<T> GetList(Expression<Func<T, bool>> whereExpression);//返回符合條件的所有數(shù)據(jù)

分頁獲取數(shù)據(jù):

public List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel page);
public List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);
public List<T> GetPageList(List<IConditionalModel> conditionalList, PageModel page);
public List<T> GetPageList(List<IConditionalModel> conditionalList, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);

其中IConditionModel是一個空的接口,用來定義規(guī)范查詢規(guī)范,實(shí)際上使用的是類:

public class ConditionalModel: IConditionalModel
{
    public ConditionalModel()
    {
        this.ConditionalType = ConditionalType.Equal;
    }
    public string FieldName { get; set; }
    public string FieldValue { get; set; }
    public ConditionalType ConditionalType { get; set; }
    public Func<string,object> FieldValueConvertFunc { get; set; }
}

那么,我們看一下 ConditionType,定義了各種判斷依據(jù):

public enum ConditionalType
{
    Equal=0,
    Like=1,
    GreaterThan =2,
    GreaterThanOrEqual = 3,
    LessThan=4,
    LessThanOrEqual = 5,
    In=6,
    NotIn=7,
    LikeLeft=8,
    LikeRight=9,
    NoEqual=10,
    IsNullOrEmpty=11,
    IsNot=12,
    NoLike = 13,
}

那么我們簡單看一下 使用IConditionModel進(jìn)行分頁是怎樣的效果:

var list = personClient.GetPageList(new List<IConditionalModel>
{
    new ConditionalModel
    {
        FieldName = "Age",
        FieldValue = "3",
        ConditionalType = ConditionalType.LessThan
    }
}, pageModel);

生成如下SQL語句:

SELECT COUNT(1) FROM (SELECT `Id`,`Name`,`Age` FROM `Person`  WHERE   Age < @ConditionalAge0  ) CountTable 
SELECT `Id`,`Name`,`Age` FROM `Person`   WHERE   Age < @ConditionalAge0      LIMIT 0,2

可以看出兩者并沒有區(qū)別,只不過是不同的查詢習(xí)慣。

6. 總結(jié)

按照之前的習(xí)慣,到目前應(yīng)該可以結(jié)束了。但是SqlSugar還有一些很重要的地方?jīng)]有介紹,所以就加個下期預(yù)告

下一篇將為大家分析SqlSugar的一些更高級的內(nèi)容,查詢的高級模式、事務(wù)以及批量操作

好,總結(jié)一下這一篇,我們在這一篇看到了SqlSugar在增刪改查上的亮點(diǎn),可以說更貼合實(shí)際業(yè)務(wù)需求開發(fā)。嗯,悄悄給個贊。

再有三篇的內(nèi)容《C# 數(shù)據(jù)操作系列》就要完結(jié)了。從下一系列開始,就要步入工作中最重要的技術(shù)棧了:Asp.net Core。這是可以寫入簡歷的。嗯,沒錯。下一系列計(jì)劃以實(shí)戰(zhàn)的形式介紹asp.net core的知識點(diǎn)和設(shè)置。

更多內(nèi)容煩請關(guān)注我的博客《高先生小屋》

file
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容