【開源框架】SqlSugarRepository 全庫ORM 正式釋出

孫凱旋發表於2016-11-20

SqlSugarRepository.dll 全庫開發框架支援 四種資料庫:SqlServer、 MySql 、Oracle和Sqlite。

SqlSugarRepository是為全庫開發而生的ORM框架,能夠做到多種資料庫之間的無間隙切換,在這一年多的時間裡,園友提出的各種需求我都已經切切實實的去做了,做到了能力範圍內的最好,一個不錯的里程碑。同時也對未來有了更明確的規劃,這只是開源的開始,Sugar ORM 還會有更多驚喜。

 

基於SqlSugar的開源CMS(百籤軟體出品)和SqlSugar官網 本月將開源 

 

 

主流ORM多庫支援情況

Dapper 有多庫訪問元件,做不了同一個查詢語句適用多種資料庫。(select * from table這種除外)

EF  有多庫訪問元件,可以做到同一個查詢適用多種資料庫,但是名稱空間引用不同需要自已用倉儲實現多庫

SqlSugarRepository 有多庫訪問元件,可以做到同一個查詢適用多種資料庫,已經實現內部工廠,比倉儲模式的應變能力更強。

 

優點:

語法具有創新並且豐富

接近原生的效能

完整的學習文件

使用方便, Nuget直接搜尋SqlSugarRepository下載便可,依賴dll都打包好了

Sugar ORM 所有成員

如果你只想操作一種資料庫,可以針對不同資料庫選擇獨立的dll

Asp.net 4.+Asp.net Core說明依賴
SqlSugar.dll SqlSugarCore.dll

SqlServer ORM  

MysqlSugar.dll MysqlSugarCore.dll

MySql ORM  

MySql.Data.dll
SqliteSugar.dll SqliteSugarCore.dll

Sqlite ORM 

System.Data.SQLite.dll

SQLite.Interop.dll(Core版不需要)

OracleSugar.dll -

Oracle ORM

Oracle.ManagedDataAccess.dll
SqlSugarRepository.dll - SqlServer MySql Sqlite Oracle 四合一

MySql.Data.dll

System.Data.SQLite.dll

Oracle.ManagedDataAccess.dll

SQLite.Interop.dll

 

 

資料庫連線

普通模式

這種模式簡單粗爆,適合一個產品支援多種資料庫,但是中間沒有兩種資料庫同時操作。

//普通連線
using (ISqlSugarClient idb = DbRepository.GetInstance(DbType.MySql, SugarDao.MySqlConnString))//DbRepository 框架現成的類,並非自定義
{ 
var list = idb.Queryable<Student>().First();
}

 

靈活模式

適合多種資料庫混用專案

//使用MyRepository連線資料庫
using (MyRepository db = new MyRepository())
{
      //當前連線的sqlconn1
      var list = db.Database.Queryable<Student>().First();

      //切換mysqlconn1
      db.SetCurrent(db.MySqlConn1);
      var list2 = db.Database.Queryable<Student>().First(); ;

}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugarRepository;

namespace NewTest.Demos
{
    public class MyRepository:DbRepository
    {
        public ConnectionConfig SqlConn1 = new ConnectionConfig() { DbType = DbType.SqlServer, ConnectionString = SugarDao.SqlConnString1 };
        public ConnectionConfig SqlConn2 = new ConnectionConfig() { DbType = DbType.SqlServer, ConnectionString = SugarDao.SqlConnString2 };
        public ConnectionConfig MySqlConn1 = new ConnectionConfig() { DbType = DbType.MySql, ConnectionString = SugarDao.MySqlConnString };
    }
}

 MyRepository為自定義類繼承 DbRepository

 

多庫支援

統一引數關鍵詞和Sqlparameter

不管操作哪個資料庫關鍵詞都是@並且用到Sqlparameter地方不需要切換成MySqlparameter這種,如下寫法:

 var student12 = db.Queryable<Student>().Where(c => c.name).Where("id>@id", new { id = 1 }).ToList();
db.SqlQuery<Student>("select * from Student where id=@id",new SqlParameter("@id","id"));

  

複雜SQL的選擇器

當ORM語法不能滿足的時候我們就需要用到原生SQL或者儲存過程,sqlbuilder可以根據當前連線哪種資料庫返回相應的SQL語句。

string sql = db.SqlBuilder()
.ToSqlServer("select top 1 id,name from student ") 
.ToOracle("select id,name from student where rownum=1") 
.ToOther("select id,name from student limit 0,1").ToString(); 

var list = db.SqlQuery<string[]>(sql).SingleOrDefault();

 

返回型別的支援

Queryable返回型別支援四種 List<T>  Dynamic   JsonString  DataTable

var student = db.Queryable<Student>().ToList();
var studentDynamic = db.Queryable<Student>().ToDynamic();
var studentJson = db.Queryable<Student>().ToJson();
var studentTable = db.Queryable<Student>().ToDataTable();

還可以這麼玩

var student = db.Queryable<Student>().Select<int>(it=>it.id).ToList();
var student2 = db.Queryable<Student>().Select<string[]>("*").ToList();
var student3 = db.Queryable<Student>().Select<Dictionary<string,object>>("id,name").ToList();

新類

var list1 = db.Queryable<Student>().Where(c => c.id < 10)
        .Select<V_Student>(c => new V_Student { id = c.id, AreaName = "預設地區" }).ToList();

匿名物件

var list2 = db.Queryable<Student>().Where(c => c.id < 10)
    .Select<V_Student>(c => new V_Student { id = c.id, AreaName = "預設地區" }).ToDynamic();

...

 

 

增刪查改

查詢

分頁亮點

int pageCount = 0;                
var page = db.Queryable<Student>().Where(c => c.id > 1).OrderBy(it => it.id).ToPageList(pageIndex,pageSize,ref pageCount);
//查詢所有
var student = db.Queryable<Student>().ToList();
var studentDynamic = db.Queryable<Student>().ToDynamic();
var studentJson = db.Queryable<Student>().ToJson();


//查詢單條
var single = db.Queryable<Student>().Single(c => c.id == 1);
//查詢單條根據主鍵
var singleByPk = db.Queryable<Student>().InSingle(1);
//查詢單條沒有記錄返回空物件
var singleOrDefault = db.Queryable<Student>().SingleOrDefault(c => c.id == 11111111);
//查詢單條沒有記錄返回空物件
var single2 = db.Queryable<Student>().Where(c => c.id == 1).SingleOrDefault();
//查詢所有的Id
var singleFieldList = db.Queryable<Student>().Select<int>(it=>it.id).ToList();

//查詢第一條
var first = db.Queryable<Student>().Where(c => c.id == 1).First();
var first2 = db.Queryable<Student>().Where(c => c.id == 1).FirstOrDefault();

//取11-20條
var page1 = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).Skip(10).Take(10).ToList();

//取11-20條  等於 Skip(pageIndex-1)*pageSize).Take(pageSize) 等於  between (pageIndex-1)*pageSize and  pageIndex*pageSize
var page2 = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).ToPageList(2, 10);

//查詢條數
var count = db.Queryable<Student>().Where(c => c.id > 10).Count();

//從第2條開始以後取所有
var skip = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).Skip(2).ToList();

//取前2條
var take = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).Take(2).ToList();

//Not like 
string conval = "a";
var notLike = db.Queryable<Student>().Where(c => !c.name.Contains(conval.ToString())).ToList();

//Like
conval = "";
var like = db.Queryable<Student>().Where(c => c.name.Contains(conval)).ToList();

//支援字串Where 讓你解決,更復雜的查詢
var student12 = db.Queryable<Student>().Where(c => "a" == "a").Where("id>@id", new { id = 1 }).ToList();
var student13 = db.Queryable<Student>().Where(c => "a" == "a").Where(
            db.Sqlbuilder()
            .ToOracle("id>100 and id in( select 1 from dual)")
            .ToOther( "id>100 and id in( select 1)").ToString()
    ).ToList();


//存在記錄反回true,則否返回false
bool isAny100 = db.Queryable<Student>().Any(c => c.id == 100);
bool isAny1 = db.Queryable<Student>().Any(c => c.id == 1);


//獲取最大Id
object maxId = db.Queryable<Student>().Max(it => it.id);
int maxId1 = db.Queryable<Student>().Max(it => it.id).ObjToInt();//拉姆達
int maxId2 = db.Queryable<Student>().Max<int>("id"); //字串寫法

//獲取最小
int minId1 = db.Queryable<Student>().Where(c => c.id > 0).Min(it => it.id).ObjToInt();//拉姆達
int minId2 = db.Queryable<Student>().Where(c => c.id > 0).Min<int>("id");//字串寫法


//order By 
var orderList = db.Queryable<Student>().OrderBy("id desc,name asc").ToList();//字串支援多個排序
//可以多個order by表達示
var order2List = db.Queryable<Student>().OrderBy(it => it.name).OrderBy(it => it.id, OrderByType.desc).ToList(); // order by name as ,order by id desc

//In
var intArray = new[] { "5", "2", "3" };
var intList = intArray.ToList();
var listnew = db.Queryable<Student>().Where(it => intArray.Contains(it.name)).ToList();
var list0 = db.Queryable<Student>().In(it => it.id, 1, 2, 3).ToList();
var list1 = db.Queryable<Student>().In(it => it.id, intArray).ToList();
var list2 = db.Queryable<Student>().In("id", intArray).ToList();
var list3 = db.Queryable<Student>().In(it => it.id, intList).ToList();
var list4 = db.Queryable<Student>().In("id", intList).ToList();
var list6 = db.Queryable<Student>().In(intList).ToList();//不設定欄位預設主鍵

//分組查詢
var list7 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy(it => it.sex).Select("sex,count(*) Count").ToDynamic();
var list8 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy(it => it.sex).GroupBy(it => it.id).Select("id,sex,count(*) Count").ToDynamic();
List<StudentGroup> list9 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy(it => it.sex).Select<StudentGroup>("Sex,count(*) Count").ToList();
List<StudentGroup> list10 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy("sex").Select<StudentGroup>("Sex,count(*) Count").ToList();
//SELECT Sex,Count=count(*)  FROM Student  WHERE 1=1  AND  (id < 20)    GROUP BY Sex --生成結果



//2表關聯查詢
var jList = db.Queryable<Student>()
.JoinTable<School>((s1, s2) => s1.sch_id == s2.id) //預設left join
.Where<School>((s1, s2) => s1.id == 1)
.Select("s1.*,s2.name as schName")
.ToDynamic();

/*等於同於
    SELECT s1.*,s2.name as schName 
    FROM [Student]  s1 
    LEFT JOIN [School]  s2 ON  s1.sch_id  = s2.id 
    WHERE  s1.id  = 1 */

//2表關聯查詢並分頁
var jList2 = db.Queryable<Student>()
.JoinTable<School>((s1, s2) => s1.sch_id == s2.id) //預設left join
    //如果要用inner join這麼寫
    //.JoinTable<School>((s1, s2) => s1.sch_id == s2.id ,JoinType.INNER)
.Where<School>((s1, s2) => s1.id > 1)
.OrderBy(s1 => s1.name)
.Skip(10)
.Take(20)
.Select("s1.*,s2.name as schName")
.ToDynamic();

//3表查詢並分頁
var jList3 = db.Queryable<Student>()
.JoinTable<School>((s1, s2) => s1.sch_id == s2.id) // left join  School s2  on s1.id=s2.id
.JoinTable<School>((s1, s3) => s1.sch_id == s3.id) // left join  School s3  on s1.id=s3.id
.Where<School>((s1, s2) => s1.id > 1)  // where s1.id>1
.Where(s1 => s1.id > 0)
.OrderBy<School>((s1, s2) => s1.id) //order by s1.id 多個order可以  .oderBy().orderby 疊加 
.Skip(10)
.Take(20)
.Select("s1.*,s2.name as schName,s3.name as schName2")//select目前只支援這種寫法
.ToDynamic();


//上面的方式都是與第一張表join,第三張表想與第二張表join寫法如下
List<V_Student> jList4 =
    db.Queryable<Student>()
    .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) // left join  School s2  on s1.id=s2.id
    .JoinTable<School, Area>((s1, s2, a1) => a1.id == s2.AreaId)// left join  Area a1  on a1.id=s2.AreaId  第三張表與第二張表關聯
    .JoinTable<Area, School>((s1, a1, s3) => a1.id == s3.AreaId)// left join  School s3  on a1.id=s3.AreaId  第四第表第三張表關聯
    .JoinTable<School>((s1, s4) => s1.sch_id == s4.id) // left join  School s2  on s1.id=s4.id
    .Select<School, Area, V_Student>((s1, s2, a1) => new V_Student { id = s1.id, name = s1.name, SchoolName = s2.name, AreaName = a1.name }).ToList();

//等同於
//SELECT id = s1.id, name = s1.name, SchoolName = s2.name, AreaName = a1.name  
//FROM [Student]   s1 
//LEFT JOIN School  s2 ON  ( s1.sch_id  = s2.id )    
//LEFT JOIN Area  a1 ON  ( a1.id  = s2.AreaId )     //第三張表與第二張表關聯
//LEFT JOIN School  s3 ON  ( a1.id  = s3.AreaId )   //第四張表與第三張表關聯
//LEFT JOIN School  s4 ON  ( s1.sch_id  = s4.id )    
//WHERE 1=1    


//Join子查詢語句加分頁的寫法
var childQuery = db.Queryable<Area>().Where("id=@id").Select(it => new { id = it.id }).ToSql();//建立子查詢SQL
//string childTableName =SqlSugarTool.PackagingSQL(childQuery.Key);//將SQL語句用()包成表
//var queryable = db.Queryable<Student>()
// .JoinTable<School>((s1, s2) => s1.sch_id == s2.id)  //LEFT JOIN School  s2 ON  ( s1.sch_id  = s2.id )  
// .JoinTable(childTableName, "a1", "a1.id=s2.areaid", new { id = 1 }, JoinType.INNER) //INNER JOIN (SELECT *  FROM [Area]   WHERE 1=1  AND id=@id   ) a1 ON a1.id=s2.areaid
// .OrderBy(s1 => s1.id);

//var list = queryable.Select<School, Area, V_Student>((s1, s2, a1) => new V_Student { id = s1.id, name = s1.name, SchoolName = s2.name, AreaName = a1.name })
//    .ToPageList(0, 200);
//var count2 = queryable.Count();


//拼接例子
var queryable2 = db.Queryable<Student>().Where(it => true);
if (maxId.ObjToInt() == 1)
{
    queryable2.Where(it => it.id == 1);
}
else
{
    queryable2.Where(it => it.id == 2);
}
var listJoin = queryable2.ToList();


//queryable和SqlSugarClient解耦
var par =DbRepository.GetISugarQueryableByType<Student>(type).Where(it => it.id == 1);//聲名沒有connection物件的Queryable
db.SetDB(par);
var listPar = par.ToList();


//檢視生成的sql和引數
var id = 1;
var sqlAndPars = db.Queryable<Student>().Where(it => it.id == id).OrderBy(it => it.id).ToSql();



//拉姆達支援的函式操作
var par1 = "2015-1-1"; var par2 = "   我 有空格A, ";
var r1 = db.Queryable<Student>().Where(it => it.name == par1.ObjToString()).ToList(); //ObjToString會將null轉轉成""
var r2 = db.Queryable<InsertTest>().Where(it => it.d1 == par1.ObjToDate()).ToList();
var r3 = db.Queryable<InsertTest>().Where(it => it.id == 1.ObjToInt()).ToList();//ObjToInt會將null轉轉成0
var r4 = db.Queryable<InsertTest>().Where(it => it.id == 2.ObjToDecimal()).ToList();
var r5 = db.Queryable<InsertTest>().Where(it => it.id == 3.ObjToMoney()).ToList();
var r6 = db.Queryable<InsertTest>().Where(it => it.v1 == par2.Trim()).ToList();
var convert1 = db.Queryable<Student>().Where(c => c.name == "a".ToString()).ToList();
var convert2 = db.Queryable<Student>().Where(c => c.id == Convert.ToInt32("1")).ToList();
var convert3 = db.Queryable<Student>().Where(c => c.name == par2.ToLower()).ToList();
var convert4 = db.Queryable<Student>().Where(c => c.name == par2.ToUpper()).ToList();
var convert5= db.Queryable<Student>().Where(c => DateTime.Now > Convert.ToDateTime("2015-1-1")).ToList();
var c1 = db.Queryable<Student>().Where(c => c.name.Contains("a")).ToList();
var c2 = db.Queryable<Student>().Where(c => c.name.StartsWith("a")).ToList();
var c3 = db.Queryable<Student>().Where(c => c.name.EndsWith("a")).ToList();
var c4 = db.Queryable<Student>().Where(c => !string.IsNullOrEmpty(c.name)).ToList();
var c5 = db.Queryable<Student>().Where(c => c.name.Equals("小杰")).ToList();
var c6 = db.Queryable<Student>().Where(c => c.name.Length > 4).ToList();
var time = db.Queryable<InsertTest>().Where(c => c.d1>DateTime.Now.AddDays(1)).ToList();
var time2 = db.Queryable<InsertTest>().Where(c => c.d1 > DateTime.Now.AddYears(1)).ToList();
var time3 = db.Queryable<InsertTest>().Where(c => c.d1 > DateTime.Now.AddMonths(1)).ToList();

 

插入

插入單條
db.Insert(GetInsertItem()); //插入一條記錄 (有主鍵也好,沒主鍵也好,有自增列也好都可以插進去)

插入多條

db.InsertRange(GetInsertList()); //批量插入 支援(別名表等功能)
db.SqlBulkCopy(GetInsertList()); //批量插入 適合海量資料插入

設定不插入列

db.DisableInsertColumns = new string[] { "sex" };//sex列將不會插入值
Student s = new Student()
{
name = "" + new Random().Next(1, int.MaxValue),
sex = "gril"
};var id = db.Insert(s); //插入
//查詢剛插入的sex是否有值
var sex = db.Queryable<Student>().Single(it => it.id == id.ObjToInt()).sex;//無值
var name = db.Queryable<Student>().Single(it => it.id == id.ObjToInt()).name;//有值

//SqlBulkCopy同樣支援不插入列設定
db.SqlBulkCopy(GetInsertList());

 

更新

//指定列更新
db.Update<School>(new { name = "藍翔14" }, it => it.id == 14); //只更新name列
db.Update<School, int>(new { name = "藍翔11 23 12", areaId = 2 }, 11, 23, 12);
db.Update<School, string>(new { name = "藍翔2" }, new string[] { "11", "21" });
db.Update<School>(new { name = "藍翔2" }, it => it.id == 100);
var array=new int[]{1,2,3};
db.Update<School>(new { name = "藍翔2" }, it => array.Contains(it.id));// id in 1,2,3


//支援字典更新,適合動態許可權
var dic = new Dictionary<string, string>();
dic.Add("name", "第十三條");
dic.Add("areaId", "1");
db.Update<School, int>(dic, 13);


//整個實體更新
db.Update(new School { id = 16, name = "藍翔16", AreaId = 1 });
db.Update<School>(new School { id = 12, name = "藍翔12", AreaId = 2 }, it => it.id == 18);
db.Update<School>(new School() { id = 11, name = "青鳥11" });

//設定不更新列
db.DisableUpdateColumns = new string[] { "CreateTime" };//設定CreateTime不更新

TestUpdateColumns updObj = new TestUpdateColumns()
{
    VGUID = Guid.Parse("542b5a27-6984-47c7-a8ee-359e483c8470"),
    Name = "xx",
    Name2 = "xx2",
    IdentityField = 0,
    CreateTime = null
};

//CreateTime將不會被更新
db.Update(updObj);
//以前實現這種更新需要用指定列的方式實現,現在就簡單多了。



//批量更新   資料量小時建議使用
var updateResult = db.UpdateRange(GetUpdateList());

//批量更新  資料量大時建議使用
var updateResult2 = db.SqlBulkReplace(GetUpdateList2());


//更新字串
db.Update<Student>("sch_id=sch_id+1", it => it.id == 1);


//清空禁止更新列
db.DisableUpdateColumns = null;
//新語法新增禁止更新列
db.AddDisableUpdateColumns("id", "name");//新增禁止更新列

 

刪除

//刪除根據主鍵
db.Delete<School, int>(10);

//刪除根據表達示
db.Delete<School>(it => it.id > 100);//支援it=>array.contains(it.id)
 
//主鍵批量刪除
db.Delete<School, string>(new string[] { "100", "101", "102" });

//非主鍵批量刪除
db.Delete<School, string>(it => it.name, new string[] { "" });
db.Delete<School, int>(it => it.id, new int[] { 20, 22 });


//根據實體賦值實體一定要有主鍵,並且要有值。
db.Delete(new School() { id = 200 });

//根據字串刪除
db.Delete<School>("id=@id", new { id = 100 });

//假刪除
//db.FalseDelete<school>("is_del", 100);
//等同於 update school set is_del=1 where id in(100)
//db.FalseDelete<school>("is_del", it=>it.id==100);

 

插入或者更新

//插入或者更新 NEW
//當主鍵值為 0 、sttring.Empty、NULL 或者 Guid.Empty時執行插操作,否則執行更新

db.AddDisableInsertColumns("UpdateTime");//禁止插入更新時間
db.AddDisableUpdateColumns("CreateTime");//禁止更新建立時間
db.InsertOrUpdate(GetInsertItem2());

 

 

 

SqlSugarORM更多用法

github 原始碼

 

 喜歡就給個推薦或者一個Star!!

相關文章