C# 數據操作系列 – 14 深入探索SqlSugar

0.前言

在上一篇中,我們知道了如何使用SqlSugar,但是也只是簡單的了解了如何使用,彷彿是套着鐐銬行走,這明顯不符合一個合格的程序員應有的素養。所以,這一篇我們將對其進行深挖,探究其背後的秘密。

1. 花式映射

在實際開發中,程序中的實體類和數據庫的表名並不能完全一致,造成的原因有很多,例如說團隊對數據庫的命名和對程序的命名有着不同的要求,數據庫是先建立的而程序是後開發的,又或者是程序只使用了數據庫中一部分表等等。

這時候就會與C#約定優於配置相違背,但是這也符合C#的設計哲學,因為配置也是C#的一部分。我們該如何從實際角度來完成表與實體類之間的關係建立呢?

那就讓我來帶着大家一起看看SqlSugar是否能優雅的完成這一部分:

1.1 Attribute設置

SqlSugar預製了一些Attribute,允許我們通過Attribute來為實體表與數據庫表之間建立關係:

  • SugarTable:用來定義實體類映射的數據表
public SugarTable(string tableName);
public SugarTable(string tableName, string tableDescription);

這是SugarTable的兩個構造函數,允許設置表名和數據表描述

  • SugarColumn:用來定義屬性與數據表中的列的關係
public string ColumnDataType { get; set; }// 列的數據類型,填SQL 的數據類型
public string OldColumnName { get; set; }// 當做了表更新之後,用來生成數據庫用,此處填寫原列名
public bool IsNullable { get; set; }// 設置列是否允許為NULL
public int Length { get; set; } // 設置列的數據長度
public string ColumnDescription { get; set; }// 設置列的描述名稱
public bool IsIdentity { get; set; } 		// 設置該列是否是自增列
public bool IsPrimaryKey { get; set; }		//設置該列是主鍵
public bool IsIgnore { get; set; }			// 不作數據庫操作,true將不會進行查詢、添加等操作
public string ColumnName { get; set; }		// 設置對應的列名
public string DefaultValue { get; set; }	// 設置該列的默認值

SqlSugar的Attribute配置非常的簡單,只需要針對類與表的映射和屬性對列的映射做出配置即可。

1.2 動態配置

與EF等一樣,SqlSugar也支持動態配置,那麼就跟着我一起去看看,如何實現動態配置吧:

SqlSugar支持的動態配置功能較少,最好是預先設計好了數據庫,然後使用動態配置做好關聯。

通過SugarClient設置數據表的動態配置:

Client.MappingTables.Add

方法有:

public void Add(string entityName, string dbTableName);
public void Add(string entityName, string dbTableName, string dbTableShortName);
public void Add(MappingTable table);

然後通過SugarClient設置列的動態配置:

Client.MmappingColumn.Add

方法有:

public void Add(string propertyName, string dbColumnName, string entityName);
public void Add(MappingColumn col);

顯然,動態配置並不支持設置列的其他內容。當然,SugarClient還可以配置忽略字段:

Client.IgnoreColumns.Add

具體實現方法如下:

public void Add(string propertyName, string EntityName);
publiv void Add(IgnoreColumn col);

1.3 As 別名模式

SqlSugar在增刪改查的時候,為數據實體添加了別名處理,使用方法As(string newName)即可。

Queryable<T>().As("newName")   //select * from newName
Insertable
Updateable
Deleteable

類似與SQL的別名查詢

2. 外鍵關聯

SqlSugar中並沒有設置導航屬性的正式加載,而是添加了一個Mapper方法:在查詢的時候,調用Mapper映射外鍵關係,以達到導航屬性一起加載的功能。

首先需要注意的是,在SqlSugar中導航屬性需要配置為忽略,避免被直接解析為SQL,否則會提示Sequence contains no elements

添加幾個示例類:

[SugarTable("P_Person")]
public class Person
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    /// <summary>
    /// 忽略
    /// </summary>
    [SugarColumn(IsIgnore = true)]
    public Employee Employee { get; set; }
}

public class Employee
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }
    public string Name { get; set; }
    public int PersonId { get; set; }
    [SugarColumn(IsIgnore = true)]
    public Person Person { get; set; }
    public int DeptId{get;set;}
    [SugarColumn(IsIgnore = true)]
    public Dept Dept{get;set;}
}

public class Dept
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }
    public string Name { get; set; }
	[SugarColumn(IsIgnore = true)]
    public List<Employee> Employees{get;set;}
}

使用上一篇的Context類:

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<Person, Employee, Dept>();
        Client.Aop.OnLogExecuting = (sql, paramters) => 
        {
            Console.WriteLine(sql);
        };
    }
}

簡單介紹一下,

InitTables這個方法,SqlSugar提供了很多重載版本,但推薦使用以下三個:

void InitTables(string entitiesNamespace);
void InitTables(string[] entitiesNamespaces);
void InitTables(params Type[] entityTypes);

前兩個,可以約定實體類的命名空間,然後一次性初始化所有實體類。第三個初始化傳入的實體類類型實例,也可以 根據一定規則反射遍歷出需要的類。

OnLogExecuting是SqlSugar 的一個監聽事件(雖然它不是事件,但我個人覺得寫成事件模式比較好),作用是監控框架執行的SQL語句,可以用來調試或者做日誌監控等。

使用Mapper查詢一對一映射類型:

var results = context.Client.Queryable<Employee>().Mapper(t=>t.Person, p=>p.PersonId).ToList();

使用Mapper查詢一對多映射類型:

var results = context.Client.Queryable<Dept>().Mapper(p => p.Employees, p => p.Employees.First().DeptId).ToList();

需要注意的是,這兩個是固定寫法。

其中,一對一要求必須從主對象開始查詢。所謂主對象就是必須持有一個外鍵指向另一個表。

一對多要求從擁有集合屬性的那段(也就是其中的「一」)開始,關聯指示為 集合.First().外鍵 。

還有一點就是SqlSugar的導航屬性必須手動加載,不會自動加載進來,所以完全不會出現深度遞歸的問題。

3. 總結

這一篇我們一起探索了如何自定義表和實體類之間的映射關係,下一篇將為大家寫一個實用的模板類,包括數據庫基本查詢功能。以上是本篇內容,期待後續哦~

更多內容煩請關注我的博客《高先生小屋》

file

Tags: