1. 程式人生 > 程式設計 >.net資料庫操作框架SqlSugar的簡單入門

.net資料庫操作框架SqlSugar的簡單入門

介紹

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 建立測試資料

建立一個字典實體

public class DataDictionary
{
public string Code { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}

建立字典表並向裡面插入測試資料  

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" });
&nbshttp://www.cppcns.com
p;datas.Add(new DataDictionary() { Code = "2",Name = "湖南省",Type = "province" }); db.CodeFirst.InitTables<DataDictionary>();//這樣就能根據實體建表了 db.Insertable(datas).ExecuteCommand();//這樣就能把資料插進資料庫了<br>

在建一個Person表 

public class Person
{
//資料庫欄位
[SqlSugar.SugarColumn(IsPrimaryKey =true,IsIdentity =true)]
public int Id { get; set; }
public string Name { get; set; }
public int SexId { get; set; }
public int CityId { get; set; }
public int ProvinceId { get; set; }

//非資料庫欄位
[SqlSugar.SugarColumn(IsIgnore =true)]
public string SexName { get; set; }
[SqlSugar.SugarColumn(IsIgnore = true)]
public string CityN
程式設計客棧
ame { get; set; } [SqlSugar.SugarColumn(IsIgnore = true)] public string ProviceName { get; set; } } 

1.2 傳統字典聯表實現缺點

如果我們要將Person中的非資料字典查詢出來那麼我們就需要寫有2種實現方式

1.連表或者子查詢 (缺點 寫起來很浪費時間)

2.將字典存到記憶體,通過記憶體賦值 (缺點 字典表超過1000條以上效能很差 ,並且不能排序,或者LIKE)

下面介紹通過SqlSugar的配置查詢解決上2面個難題

1.3 配置表簡化字典聯表

配置字典表

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中的用法使用迴圈都不要
}

配置完我們查詢就會很方便了

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 簡單聯表查詢也可以配置

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

[TenantAttribute("1")]
public class C1Table
{
public string Id { get; set; }
}

[TenantAttribute("2")]
public class C2Table
{
public string Id { get; set; }
}

下面我們倉儲就可以通過實體配置自動識別是連線哪個庫

public class Repository<T> : SimpleClient<T> where T : class,new()
{
public Repository(ISqlSugarClient context = null) : base(context)//注意這裡要有預設值等於null
{
if (context == null)
{
var db = new SqlSugarClient(new List<ConnectionConfig> {
new ConnectionConfig()
&http://www.cppcns.comnbsp;{
ConfigId="1",DbType = SqlSugar.DbType.SqlServer, 程式設計客棧;IsAutoCloseConnection = true,ConnectionString = Config.ConnectionString
},new ConnectionConfig()
{
ConfigId="2",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();
}

}

新版本還添加了切換倉儲功能

public class C1Service : Repository<C1Table>
{
public void Test()
{
base.AsTenant().BeginTran();

base.GetList(); //呼叫內部倉儲方法
base.ChangeRepository<Repository<C2Table>>().GetList();//呼叫外部倉儲

base.AsTenant().CommitTran();
}
}

3、行列互轉功能 

第一個引數 列名、第二個引數 頭行名、第三個引數 值

var test06 = db.Queryable<Order>()
.ToPivotTable(it => it.Id,it => it.Sum(x => x.Price));//返回Datatable

var test07 = db.Queryable<Order>()
.ToPivotList(it => it.Id,it => it.Sum(x => x.Price));//返回List<dynamic><br>
var test08 = db.Queryable<Order>()
.ToPivotjson(it => it.Id,it => it.Sum(x => x.Price));//返回Json

.NET資料庫框架原始碼

官網地址:https://www.donet5.comhttp://www.cppcns.com/Home/Doc

以上就是.net資料庫操作框架SqlSugar的簡單入門的詳細內容,更多關於.net資料庫操作框架SqlSugar的資料請關注我們其它相關文章!