官方參考:http://www.codeisbug.com/Doc/8
前言:這應該是目前最好用的ORM框架之一了,而且支持.net core,網上除了官方文檔其他參考就少了點,自己整理了一下,大致包括:
· 概念
· 一個小demo(會涉及到T4模板生成Model)
· 常見用法(增刪改查)
數據庫是sqlserver2012,vs2017版本的,其他還有什么想到再補充。
(2019-12-15更新:大半年沒上博客今天看到郵件評論提醒上來看一下,當時沒有想到這篇筆記會有那么多人看,我現在自己回看實在汗顏,寫的啥玩意兒,尤其是配置那塊,當時也是copy的項目代碼,再后來因為離職也忘了更新代碼,而現在我已經用不到sqlsugar了,不過也正因為如此,才更覺得sqlsugar好用,對於一些沒有自己框架的小公司小項目其實是個不錯的選擇。年底我會抽空重新寫個項目,這篇權且看看好了)
一:概念
1.優勢
支持.NET 4.0+ 和 .NET CORE
支持主流數據庫:SQL Server,MySql,Oracle,Sqlite等;
2.安裝
Nuget直接搜索
項目是Core安裝sqlSugarCore版本,.Net安裝sqlSugar。
3.連接
通過參數ConnnectionConfig創建連接,ConnectionConfig有6個屬性:
1. ConnectionString: 連接字符串 (必填)
2. Data Type: 數據庫類型 (必填)
3. IsAutoCloseConnection: 是否自動釋放數據庫,默認false
4. InitKeyType: 讀取主鍵和自增列信息的方式,默認SystemTable
5. More Settings: 全局設置
6. ConfigureExternalServices: 可以擴展你想要的序列化方式和緩存方式等服務
例:
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.SystemTable
});
不過后面的版本有變動,以下是4.6.1版本的:
SqlSugar對象不能是靜態變量,但可以是靜態屬性。
例:
Public static SqlSugarClient Instance
{
get => new SqlSugarClient(xx);
]
Var db = 類.Instance;
db.Queryable<T>().ToList;
二:項目實例
1:新建項目:.net core
我選擇空模板,其他的也行,建議MVC
2.添加兩個類庫(我習慣分層寫,也可以不分層)
一定是添加不要在上面新建
3.在ORM層安裝sqlSugar,.net選第一個就好了
4.使用T4模板生成Model
a.先在sql server中建好表,數據庫名:SqlSugarDemo
[表Student]:
b.右鍵項目->添加文本模板,名字隨便起,后綴tt
c.寫好tt模板保存一下就會刷新出model,Teacher和Course表先不用管
(tt模板里的內容自行百度,我照搬公司的就不貼了,其實都差不多,SqlSugarBase.cs是下一步建的,我截圖晚了)
5.在ORM層新建SqlSugarBase類,用來提供DB訪問對象,代碼可以參考官方文檔:(代碼已修正,本頁最底下)

using SqlSugar; namespace SqlSugarDemo.ORM { public class SqlSugarBase { public static string DB_ConnectionString { get; set; } public static SqlSugarClient DB { get => new SqlSugarClient(new ConnectionConfig() { ConnectionString = DB_ConnectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true, InitKeyType = InitKeyType.SystemTable, IsShardSameThread = true } ); } } }
6.配置Startup.cs和appsettings.json,跟我一樣建空模板的要在Web層(API)手動添加:(代碼已修正,本頁最底下)

using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SqlSugarDemo.ORM; namespace SqlSugarDemo { public class Startup { readonly private IConfiguration _Configuration; public Startup(IConfiguration configuration) { this._Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); SqlSugarBase.DB_ConnectionString = this._Configuration.GetConnectionString("connectionString"); //為數據庫連接字符串賦值 } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default1", template: "{controller=Home}/{action=Index}/{id?}"); }); } //public void Configure(IApplicationBuilder app, IHostingEnvironment env) //{ // if (env.IsDevelopment()) // { // app.UseDeveloperExceptionPage(); // } // app.Run(async (context) => // { // await context.Response.WriteAsync("Hello World!"); // }); //} } }
以上代碼有參考:https://www.cnblogs.com/kuangliwen/p/7895646.html

"connectionString": "Server=127.0.0.1;Database=SqlSugarDemo;Integrated Security=False;User ID=sa;Password=sa;", "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } } }
7.添加邏輯代碼和控制類(可以不分開寫)
在Service層右鍵添加HomeService.cs

using SqlSugarDemo.ORM; using SqlSugarDemo.ORM.Entity; using System.Collections.Generic; namespace SqlSugarDemo.Service { public class HomeService : SqlSugarBase { public List<Student> GetList() { return DB.Queryable<Student>().ToList(); } } }
DB.Queryable<Student>().ToList(); 相當於select * from Student
在Web層右鍵添加HomeController.cs(代碼已修正,本頁最底下)

using Microsoft.AspNetCore.Mvc; using SqlSugarDemo.Service; namespace SqlSugarDemo.API { public class HomeController : Controller { readonly HomeService _HomeService; public HomeController(HomeService homeService) { _HomeService = homeService; } [HttpGet] public IActionResult Index() { var result = _HomeService.GetList(); ViewBag.Result = result; return View(); } } }
8.最后別忘了添加Index頁面
最終項目結構:
我覺得這個項目結構不是很好,隨意看看
編譯通過,運行我報500的錯誤(慘兮兮),原因還在找,可能第6步有點問題,所以不能驗證結果,反正過程大致是這么個過程。
//0810更新:數據庫連接有問題,稍后修改
//0813更新:全部代碼已修改完畢,詳見底部
三:SqlSugar常用方法總結
先上之前的三張表:
[Student]
[Teacher]
[Course]
很簡單的三張表,Id都是主鍵自增,其中Student.CourseId = Course.Code = Teacher.CourseId
【查詢】
1. 查詢所有
var result = DB.Queryable<Student>().ToList();
相當於 :
select * from Student;
2. 跟據主鍵查詢:id為方法參數
var result = DB.Queryable<Student>().InSingle(id);
相當於 :
select * from Student where Id = id;
3. 根據給定的字段查詢:name為方法參數
var result = DB.Queryable<Student>().Where(s => s.Name == name);
相當於:
select * from Student where Name = name;
4. 模糊查詢:方法參數key為關鍵字
var result = DB.Queryable<Student>().Where(s => s.Name.Contains(key)).ToList();
相當於:
select * from Student where Name like ‘%key%’;
5. 雙表查詢
var result = DB.Queryable<Student, Teacher>((a, b) => new object[] { JoinType.Left,a.CourseId==b.CourseId}) .Select((a, b) => new { Student = a.Name, Teacher = b.Name }).ToList();
以上將結果返回匿名對象,要是返回實體對象,第三行new 一個model就行了。
相當於:
select Student.Name student,Teacher.Name teacher
from Student
left join Teacher
on Student.CourseId = Teacher.CourseId;
6. 三表查詢,根據給定id查詢學生姓名,老師和課程名稱
var result = DB.Queryable<Student, Teacher, Course>((a, b, c) => new object[] { JoinType.Left,a.CourseId == b.CourseId, JoinType.Left,b.CourseId == c.Code }) .Where(a => a.Id == id) .Select((a, b, c) => new { Student = a.Name, Teacher = b.Name,Course = c.name }).ToList();
以上同樣返回匿名對象
相當於:
select Student.Name student,Teacher.Name teacher,Course.name course
from Student
left join Teacher
on Student.CourseId = Teacher.CourseId
left join Course
on Course.Code = Teacher.CourseId
where Student.Id = id;
7. 分頁,以第四條為例,方法參數pageIndex為頁數,pageSize為條數
var result = DB.Queryable<Student>().Where(s => s.Name.Contains(key)).ToPageList(pageIndex, pageSize).ToList();
【刪除】
1. 根據主鍵刪除,id為方法參數
var result = DB.Deleteable<Student>().In(id).ExecuteCommand();
相當於:
Delete from Student where Id = id;
2. 根據主鍵批量刪除,ids為方法參數
var result = DB.Deleteable<Student>().In(ids).ExecuteCommand();
3. 根據給定字段刪除,name為方法參數
var result = DB.Deleteable<Student>().Where(s => s.Name == name).ExecuteCommand();
相當於:
Delete from Student where Name = name;
4. 批量刪除,key為關鍵字
var result = DB.Deleteable<Student>().Where(s => s.Name.Contains(key)).ExecuteCommand();
相當於:
Delete from Student where Name like’%a%’;
【添加】
以向表Student添加數據為例:
public bool Insert() { Student model = new Student(); model.StuId = 8; model.Name = "abc"; model.CourseId = 2; var test = DB.Insertable(model).ExecuteCommand(); return test > 0; }
ps:關鍵就是:DB.Insertable(model).ExecuteCommand() 這一句。
<StudentModel>不一定要寫,可以使用匿名對象;
model賦值也可以放到添加方法里,比如:
var test = DB.Insertable(new StudentModel
{
Name = "abc",
//這里想要添加幾個字段就寫幾個
}).ExecuteCommand()
【更新】
跟添加類似,DB.Insertable(model).ExecuteCommand() 改為 DB.Updateable(model).ExecuteCommand();
代碼修改:
Startup.cs:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices (IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }
SqlSuagrBase:(連接字符串本來應該在appsettings里的,這個示范不太好,不過作為小demo就不考慮那么多了)
public abstract class SqlSugarBase { public SqlSugarClient DB => GetInstance(); SqlSugarClient GetInstance() { string connectionString = "Server=127.0.0.1;Database=SqlSugarDemo;Integrated Security=False;User ID=sa;Password=sa;"; var db = new SqlSugarClient( new ConnectionConfig { ConnectionString = connectionString, DbType = DbType.SqlServer, IsShardSameThread = true } ); return db; } }
Home Controller:這里把Index刪了,重新寫了查詢方法,View里面的Index也可以不用了。
[HttpGet] public List<Student> GetList() { var result = _HomeService.GetList(); return result; }
代碼到這里就結束了,下面我添加了一個單元測試來測試這個方法(引用Xunit),測試通過。
代碼我整理一下再貼上來。