OracleSugar ORM框架的诞生,代码开源

时间:2023-01-08 23:09:43

经过四天的努力终于将SqlSugar ORM 成功支持ORACLE数据库

OracleSugar ORM框架的诞生,代码开源

优点:

1、高性能,达到原生最高水准,比SqlHelper性能要高,比Dapper快30% 比EF快50%

2、支持多种数据库 ,sql版本更新最快,其它会定期更新,可以在多种数据库用一种编程方式

3、支持.net Core

4、支持多库并行计算

5、带有实体生成函数和T4模版生成实体

6、无需任何配置 ,还你一个干净的model

2、功能介绍/Product function introduction

查询/Search

1、Queryable用于拉姆达操作数据库

2、SqlQuery用于执行SQL和存储过程

3、Sqlable一种更新近SQL的写法

1、Queryable 用于拉姆达表达式操作(支持Join多表)    / Select single table or view

   //查询所有
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 == );
//查询单条没有记录返回空对象
var singleOrDefault = db.Queryable<STUDENT>().SingleOrDefault(c => c.ID == );
//查询单条没有记录返回空对象
var single2 = db.Queryable<STUDENT>().Where(c => c.ID == ).SingleOrDefault(); //查询第一条
var first = db.Queryable<STUDENT>().Where(c => c.ID == ).First();
var first2 = db.Queryable<STUDENT>().Where(c => c.ID == ).FirstOrDefault(); //取10-20条
var page1 = db.Queryable<STUDENT>().Where(c => c.ID > ).OrderBy(it => it.ID).Skip().Take().ToList(); //上一句的简化写法,同样取10-20条
var page2 = db.Queryable<STUDENT>().Where(c => c.ID > ).OrderBy(it => it.ID).ToPageList(, ); //查询条数
var count = db.Queryable<STUDENT>().Where(c => c.ID > ).Count(); //从第2条开始以后取所有
var skip = db.Queryable<STUDENT>().Where(c => c.ID > ).OrderBy(it => it.ID).Skip().ToList(); //取前2条
var take = db.Queryable<STUDENT>().Where(c => c.ID > ).OrderBy(it => it.ID).Take().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 = }).ToList();
var student13 = db.Queryable<STUDENT>().Where(c => "a" == "a").Where("id>100 ").ToList(); //存在记录反回true,则否返回false
bool isAny100 = db.Queryable<STUDENT>().Any(c => c.ID == );
bool isAny1 = db.Queryable<STUDENT>().Any(c => c.ID == ); //获取最大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<STUDENT, int>("id"); //字符串写法 //获取最小
int minId1 = db.Queryable<STUDENT>().Where(c => c.ID > ).Min(it => it.ID).ObjToInt();//拉姆达
int minId2 = db.Queryable<STUDENT>().Where(c => c.ID > ).Min<STUDENT, 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[] { "", "", "" };
var intList = intArray.ToList();
var list0 = db.Queryable<STUDENT>().In(it => it.ID, , , ).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 list7 = db.Queryable<STUDENT>().Where(c => c.ID < ).GroupBy(it => it.SEX).Select("sex,count(*) count").ToDynamic();
var list8 = db.Queryable<STUDENT>().Where(c => c.ID < ).GroupBy(it => it.SEX).GroupBy(it => it.ID).Select("id,sex,count(*) count").ToDynamic();
List<SexTotal> list9 = db.Queryable<STUDENT>().Where(c => c.ID < ).GroupBy(it => it.SEX).Select<STUDENT, SexTotal>("SEX,count(*) COUNT").ToList();
List<SexTotal> list10 = db.Queryable<STUDENT>().Where(c => c.ID < ).GroupBy("sex").Select<STUDENT, SexTotal>("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<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) //默认left join
.Where<STUDENT, SCHOOL>((s1, s2) => s1.ID == )
.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<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) //默认left join
//如果要用inner join这么写
//.JoinTable<Student, School>((s1, s2) => s1.sch_id == s2.id ,JoinType.INNER)
.Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > )
.OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.NAME)
.Skip()
.Take()
.Select("s1.*,s2.name as schName")
.ToDynamic(); //3表查询并分页
var jList3 = db.Queryable<STUDENT>()
.JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join School s2 on s1.id=s2.id
.JoinTable<STUDENT, SCHOOL>((s1, s3) => s1.SCH_ID == s3.ID) // left join School s3 on s1.id=s3.id
.Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > ) // where s1.id>1
.Where<STUDENT>(s1 => s1.ID > )
.OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多个order可以 .oderBy().orderby 叠加
.Skip()
.Take()
.Select("s1.*,s2.name as schName,s3.name as schName2")//select目前只支持这种写法
.ToDynamic(); //上面的方式都是与第一张表join,第三张表想与第二张表join写法如下
List<classNew> jList4 = db.Queryable<STUDENT>()
.JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join School s2 on s1.id=s2.id
.JoinTable<STUDENT, SCHOOL, AREA>((s1, s2, a1) => a1.ID == s2.AREAID)// left join Area a1 on a1.id=s2.AreaId
.Select<STUDENT, SCHOOL, AREA, classNew>((s1, s2, a1) => new classNew { NEWID = s1.ID, STUDENTNAME = s1.NAME, SCHOOLNAME = s2.NAME, AREANAME = a1.NAME }).ToList(); //最多支持5表查询,太过复杂的建议用Sqlable或者SqlQuery,我们的Queryable只适合轻量级的查询 //拼接
var queryable = db.Queryable<STUDENT>().Where(it => true);
if (maxId.ObjToInt() == )
{
queryable.Where(it => it.ID == );
}
else
{
queryable.Where(it => it.ID == );
}
var listJoin = queryable.ToList(); //queryable和SqlSugarClient解耦
var par = new Queryable<STUDENT>().Where(it => it.ID == );//声名没有connection对象的Queryable
par.DB = db;
var listPar = par.ToList(); //查看生成的sql和参数
var id=;
var sqlAndPars = db.Queryable<STUDENT>().Where(it => it.ID == id).OrderBy(it => it.ID).ToSql(); //函数的支持(字段暂不支持函数,只有参数支持) 目前只支持这么多
var par1 = "2015-1-1"; var par2 = " 我 有空格, ";
var r1 = db.Queryable<STUDENT>().Where(it => it.NAME == par1.ObjToString()).ToSql(); //ObjToString会将null转转成""
var r2 = db.Queryable<INSERTTEST>().Where(it => it.D1 == par1.ObjToDate()).ToSql();
var r3 = db.Queryable<INSERTTEST>().Where(it => it.ID == .ObjToInt()).ToSql();//ObjToInt会将null转转成0
var r4 = db.Queryable<INSERTTEST>().Where(it => it.ID == .ObjToDecimal()).ToSql();
var r5 = db.Queryable<INSERTTEST>().Where(it => it.ID == .ObjToMoney()).ToSql();
var r6 = db.Queryable<INSERTTEST>().Where(it => it.V1 == par2.Trim()).ToSql();
var convert1 = db.Queryable<STUDENT>().Where(c => c.NAME == "a".ToString()).ToList();
var convert2 = db.Queryable<STUDENT>().Where(c => c.ID == Convert.ToInt32("")).ToList();//
var convert3 = db.Queryable<STUDENT>().Where(c => DateTime.Now > Convert.ToDateTime("2015-1-1")).ToList();
var convert4 = db.Queryable<STUDENT>().Where(c => DateTime.Now > DateTime.Now).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();

2、SqlQuery 用于执行原生SQL和存储过程   /   Execution of native SQL

using (var db = SugarDao.GetInstance())
{
//转成list
List<STUDENT> list1 = db.SqlQuery<STUDENT>("select * from Student");
//转成list带参
List<STUDENT> list2 = db.SqlQuery<STUDENT>("select * from Student where id=:id", new { id = });
//转成dynamic
dynamic list3 = db.SqlQueryDynamic("select * from student");
//转成json
string list4 = db.SqlQueryJson("select * from student");
//返回int
var list5 = db.SqlQuery<int>("select id from Student where rownum=1").SingleOrDefault();
//反回键值
Dictionary<string, string> list6 = db.SqlQuery<KeyValuePair<string, string>>("select id,name from Student").ToDictionary(it => it.Key, it => it.Value);
//反回List<string[]>
var list7 = db.SqlQuery<string[]>("select id,name from Student where rownum=1").SingleOrDefault(); //存储过程
//var spResult = db.SqlQuery<SCHOOL>(@"begin exec sp_school (:p1,:p2); end;", new { p1 = 1, p2 = 2 }); //获取第一行第一列的值
string v1 = db.GetString("select '张三' as name from dual");
int v2 = db.GetInt("select 1 as name from dual");
double v3 = db.GetDouble("select 1 as name from dual");
decimal v4 = db.GetDecimal("select 1 as name from dual");
//....
}

3、Sqlable 更贴近SQL的一种编程方式,适用于复杂查询 / Complex query

 //多表查询
List<SCHOOL> dataList = db.Sqlable()
.From("school", "s")
.Join("student", "st", "st.id", "s.id", JoinType.INNER)
.Join("student", "st2", "st2.id", "st.id", JoinType.LEFT)
.Where("s.id>100 and s.id<:id")
.Where("1=1")//可以多个WHERE
.OrderBy("s.id")
.SelectToList<SCHOOL/*新的Model我这里没有所以写的School*/>("st.*", new { id = }); //多表分页
List<SCHOOL> dataPageList = db.Sqlable()
.From("school", "s")
.Join("student", "st", "st.id", "s.id", JoinType.INNER)
.Join("student", "st2", "st2.id", "st.id", JoinType.LEFT)
.Where("s.id>100 and s.id<100")
.SelectToPageList<SCHOOL>("st.*", "s.id", , ); //多表分页WHERE加子查询
List<SCHOOL> dataPageList2 = db.Sqlable()
.From("school", "s")
.Join("student", "st", "st.id", "s.id", JoinType.INNER)
.Join("student", "st2", "st2.id", "st.id", JoinType.LEFT)
.Where("s.id>100 and s.id<100 and s.id in (select 1 as id from dual )" /*这里面写子查询都可以*/)
.SelectToPageList<SCHOOL>("st.*", "s.id", , ); //--------转成List Dynmaic 或者 Json-----// //不分页
var list1 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToDynamic("*", new { id = });
var list2 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToJson("*", new { id = });
var list3 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToDataTable("*", new { id = }); //分页
var list4 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToPageDynamic("s.*", "l.id", , , new { id = });
var list5 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToPageTable("s.*", "l.id", , , new { id = });
var list6 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToPageDynamic("s.*", "l.id", , , new { id = }); //--------拼接-----//
Sqlable sable = db.Sqlable().From<STUDENT>("s").Join<SCHOOL>("l", "s.sch_id", "l.id", JoinType.INNER);
string name = "a";
int id = ;
if (!string.IsNullOrEmpty(name))
{
sable = sable.Where("s.name=:name");
}
if (!string.IsNullOrEmpty(name))
{
sable = sable.Where("s.id=:id or s.id=100");
}
if (id > )
{
sable = sable.Where("l.id in (select id from school where rownum<10)");//where加子查询
}
var pars = new { id = id, name = name };
int pageCount = sable.Count(pars);
var list7 = sable.SelectToPageList<STUDENT>("s.*", "l.id desc", , , pars);

4、新容器转换 / To new container

 using (SqlSugarClient db = SugarDao.GetInstance())
{
var list2 = db.Queryable<STUDENT>().Where(c => c.ID < ).Select(c => new classNew { NEWID = c.ID, NEWNAME = c.NAME, XX_NAME = c.NAME }).ToList();//不支持匿名类转换,也不建议使用 var list3 = db.Queryable<STUDENT>().Where(c => c.ID < ).Select(c => new { newid = c.ID, newname = c.NAME, xx_name = c.NAME }).ToDynamic();//匿名类转换 var list4 = db.Queryable<STUDENT>().Where(c => c.ID < ).Select("id as newid, name as newname ,name as xx_name").ToDynamic();//匿名类转换 var jList1 = db.Queryable<STUDENT>()
.JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join School s2 on s1.id=s2.id
.Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > ) // where s1.id>1
.OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多个order可以 .oderBy().orderby 叠加
.Skip()
.Take()
.Select<STUDENT, SCHOOL, classNew>((s1, s2) => new classNew() { NEWID = s1.ID, NEWNAME = s2.NAME, XX_NAME = s1.NAME })//select目前只支持这种写法
.ToList(); var jList2 = db.Queryable<STUDENT>()
.JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join School s2 on s1.id=s2.id
.Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > ) // where s1.id>1
.OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多个order可以 .oderBy().orderby 叠加
.Skip()
.Take()
.Select<STUDENT, SCHOOL, classNew>((s1, s2) => new classNew() { NEWID = s1.ID, NEWNAME = s1.NAME, XX_NAME = s1.NAME })//select目前只支持这种写法
.ToDynamic(); var jList3 = db.Queryable<STUDENT>()
.JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join School s2 on s1.id=s2.id
.Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > ) // where s1.id>1
.OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多个order可以 .oderBy().orderby 叠加
.Skip()
.Take()
.Select<STUDENT, classNew>(s1 => new classNew() { NEWID = s1.ID, NEWNAME = s1.NAME, XX_NAME = s1.NAME })//select目前只支持这种写法
.ToDynamic();
}

添加/Add

            //设置序列,程序起动时设置一次便可
OracleConfig.SequenceMapping = new List<PubModel.SequenceModel>()
{
new PubModel.SequenceModel(){ ColumnName="ID", TableName="STUDENT", Value="SEQ_D"}
};
using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接
{ STUDENT s = new STUDENT()
{
NAME = "张" + new Random().Next(, int.MaxValue)
}; db.Insert(s); //插入一条记录 (有主键也好,没主键也好,有自增列也好都可以插进去) List<STUDENT> list = new List<STUDENT>()
{
new STUDENT()
{
NAME="张"+new Random().Next(,int.MaxValue)
},
new STUDENT()
{
NAME="张"+new Random().Next(,int.MaxValue)
}
}; db.InsertRange(list); //批量插入
}

更新/Update

            int id = ;
using (var db = SugarDao.GetInstance())
{
//指定列更新
db.Update<SCHOOL>(new { name = "蓝翔14" }, it => it.ID == );
db.Update<SCHOOL, int>(new { name = "蓝翔11 23 12", areaId= }, , , );
db.Update<SCHOOL, string>(new { name = "蓝翔2" }, new string[] { "", "" });
db.Update<SCHOOL>(new { name = "蓝翔2" }, it => it.ID == id); //支持字段指定列更新,适合动态权限
var dic =new Dictionary<string, string>();
dic.Add("name","第十三条");
dic.Add("areaId", "");
db.Update<SCHOOL,int>(dic, );
db.Update<SCHOOL>(dic, it => it.ID == ); //整个实体更新
db.Update(new SCHOOL { ID = , NAME = "蓝翔16", AREAID= });
db.Update<SCHOOL>(new SCHOOL { ID = id, NAME = "蓝翔18", AREAID= }, it => it.ID == );
db.Update<SCHOOL>(new SCHOOL() { ID = , NAME = "xx" }); //设置不更新列
db.DisableUpdateColumns = new string[] { "CreateTime" };//设置CreateTime不更新 TESTUPDATECOLUMNS updObj = new TESTUPDATECOLUMNS()
{
VGUID = "542b5a27-6984-47c7-a8ee-359e483c8470",
NAME = "xx",
NAME2 = "xx2",
IDENTITYFIELD = ,
CREATETIME = null
}; //CreateTime将不会被更新
db.Update(updObj);
//以前实现这种更新需要用指定列的方式实现,现在就简单多了。 }

删除和假删除/Delete And False Delete

using (var db = SugarDao.GetInstance())
{
//真删除
db.Delete<School, int>();//注意主键必需为实体类的第一个属性
db.Delete<School>(it => it.id > );
db.Delete<School, string>(new string[] { "", "", "" }); //假删除
//db.FalseDelete<school>("is_del", 100);
//等同于 update school set is_del=0 where id in(100)
//db.FalseDelete<school>("is_del", it=>it.id==100);
}

删除

全局过滤器/ Gobal Filter

这功能主要用于通用权限设计等功能, 当有很多WHERE重复,并且动态 这时候就需要在全局设置好过滤器接口集合,程序中使用只需要设KEY便可

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OracleSugar;
using Models; namespace WebTest.Demo
{
/// <summary>
/// 过滤器
/// </summary>
public partial class Filter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlSugarClient db = SugarDaoFilter.GetInstance())//开启数据库连接
{
//设置走哪个过滤器
db.CurrentFilterKey = "role"; //queryable
var list = db.Queryable<STUDENT>().ToList(); //通过全局过滤器对需要权限验证的数据进行过滤
//相当于db.Queryable<Student>().Where("id=@id",new{id=1}) //sqlable
var list2 = db.Sqlable().From<STUDENT>("s").SelectToList<STUDENT>("*");
//同上 //sqlQuery
var list3 = db.SqlQuery<STUDENT>("select * from Student WHERE 1=1");
//同上
}
}
}
/// <summary>
/// 扩展SqlSugarClient
/// </summary>
public class SugarDaoFilter
{
//禁止实例化
private SugarDaoFilter()
{ }
/// <summary>
/// 页面所需要的过滤函数
/// </summary>
private static Dictionary<string, Func<KeyValueObj>> _filterParas = new Dictionary<string, Func<KeyValueObj>>()
{
{ "role",()=>{
return new KeyValueObj(){ Key=" id=:id" , Value=new{ id=}};
}
},
{ "org",()=>{
return new KeyValueObj(){ Key=" orgId=:orgId" , Value=new{ orgId=}};
}
},
};
public static SqlSugarClient GetInstance()
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //这里可以动态根据cookies或session实现多库切换
var reval = new SqlSugarClient(connection);
reval.SetFilterFilterParas(_filterParas);
return reval;
}
}
}

行列同时过滤 2.7.07

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OracleSugar;
using Models; namespace WebTest.Demos
{/// <summary>
/// 过滤器 (查询行过滤加查询列过滤)
/// </summary>
public partial class Filter2 : System.Web.UI.Page
{ protected void Page_Load(object sender, EventArgs e)
{
using (SqlSugarClient db = SugarDaoFilter.GetInstance())//开启数据库连接
{
//设置走哪个过滤器
db.CurrentFilterKey = "role"; //queryable
var list = db.Queryable<STUDENT>().ToJson(); //设置走哪个过滤器
db.CurrentFilterKey = "org"; //queryable
var list2 = db.Queryable<STUDENT>().ToJson(); }
}
}
/// <summary>
/// 扩展SqlSugarClient
/// </summary>
public class SugarDaoFilter
{
//禁止实例化
private SugarDaoFilter()
{ }
/// <summary>
/// 页面所需要的过滤行
/// </summary>
private static Dictionary<string, Func<KeyValueObj>> _filterParas = new Dictionary<string, Func<KeyValueObj>>()
{
{ "role",()=>{
return new KeyValueObj(){ Key=" id=:id" , Value=new{ id=}};
}
},
{ "org",()=>{
return new KeyValueObj() { Key = " id=:id", Value = new { id = } };
}
},
};
/// <summary>
/// 页面所需要的过滤列
/// </summary>
private static Dictionary<string, List<string>> _filterColumns = new Dictionary<string, List<string>>()
{
{ "role",new List<string>(){"id","name"}
},
{ "org",new List<string>(){"name"}
},
};
public static SqlSugarClient GetInstance()
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //这里可以动态根据cookies或session实现多库切换
var reval = new SqlSugarClient(connection); //支持sqlable和queryable
reval.SetFilterFilterParas(_filterParas); //列过滤只支持queryable
reval.SetFilterFilterParas(_filterColumns);
return reval;
}
} }

无参模式/No Parameter

将IsGetPageParas设为true之后页面的参数都不需要使用  new{}来赋值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OracleSugar;
using WebTest.Dao;
using Models; namespace WebTest.Demo
{
/// <summary>
/// 偷懒我就不给参数赋值
/// </summary>
public partial class NoParameter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{ using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接
{ db.IsGetPageParas = true;//使用无参模式直接将Requst中的ID传给@id无需在代码中写出来 var list = db.Queryable<STUDENT>().Where("id=:id").ToList(); //sqlable queryable sqlquery通用 //获取页面所有参数到键值对
//var kvs= SqlSugarTool.GetParameterDictionary(); //以前写法
//var xx = db.Queryable<Student>().Where("id=@id", new { id=Request["id"] }).ToList();
}
}
catch (Exception)
{ throw new Exception("请在当前页面URL地址后面加上参数?id=1");
}
}
}
}

事务 /Transaction

 using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接
{
db.IsNoLock = true;//启用无锁查询
db.CommandTimeOut = ;//设置超时时间
try
{
db.BeginTran();//开启事务 db.CommitTran();//提交事务
}
catch (Exception)
{
db.RollbackTran();//回滚事务
throw;
}
}

事务

公开函数 /Common Method

 //ToJoinSqlInVal
var par = new string[] { "a", "c", "" };
var ids = par.ToJoinSqlInVal();//将数组转成 'a','c','3' 有防SQL注入处理 //ToSqlValue
try
{
var par2 = "a'";
var newpar2 = par2.ToSqlValue();//对字符串防注入处理
}
catch (Exception ex)
{ Response.Write(ex.Message);
} //SqlLikeWordEncode 处理LIKE特殊字符
var likestr = SqlSugarTool.SqlLikeWordEncode("[%%%"); //GetParameterArray 获取页面参数所有参数的键和值
var pars = SqlSugarTool.GetParameterArray(); //将匿名对象转成SqlParameter
var par3= SqlSugarTool.GetParameters(new { id=});

函数

实体生成 /Create Entity File

          //根据当前数据库生成所有表的实体类文件 (参数:SqlSugarClient ,文件目录,命名空间)
db.ClassGenerating.CreateClassFiles(db, Server.MapPath("~/Models"), "Models");
//根据表名生成实体类文件
//db.ClassGenerating.CreateClassFilesByTableNames(db, Server.MapPath("~/Models"), "Models" , "student","school"); //根据表名生成class字符串
var str = db.ClassGenerating.TableNameToClass(db, "Student"); var dynamicToClassStr= db.ClassGenerating.DynamicToClass(new { id=},"dyName"); //根据SQL语句生成class字符串
var str2 = db.ClassGenerating.SqlToClass(db, "select * from Student where rownum=1", "student"); //改变值(lassTemplate.ItemTemplate=XXXX)可以自定义格式
var tempItem=ClassTemplate.ItemTemplate;
var temp=ClassTemplate.Template ;

T4模版

详细教程:

http://www.cnblogs.com/sunkaixuan/p/5751503.html

别名表/Rename table name

                //-----单个-------//
var list = db.Queryable<V_Student>("Student").ToList();//查询的是 select * from student 而我的实体名称为V_Student //-----全局多个设置-------// //设置 Mapping Table 如果没这方面需求可以传NULL
List<KeyValue> mappingTableList = new List<KeyValue>(){
new KeyValue(){ Key="FormAttr", Value="Flow_FormAttr"},
new KeyValue(){ Key="Student3", Value="Student"}
};
db.SetMappingTables(mappingTableList);

别名表

排除非数据库列 SqlSugar2.7新功能

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlSugar;
using WebTest.Dao;
using WebTest.TestLib; namespace WebTest.Demos
{
public partial class IgnoreErrorColumns : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlSugarClient db = SugarDao.GetInstance())
{ //设置别名表具体例子看rename.aspx,不是该例子的重点
db.SetMappingTables(new List<KeyValue>() { new KeyValue() { Key = "MyStudent", Value = "Student" }, });

//重点来了
//数据库并没有appendField和appendField2二个字段,设置该属性后将插入可以正常使用
db.IsIgnoreErrorColumns = true;//自动排除非数据库列 update也一样 db.Insert<MyStudent>(new MyStudent() { name = "张三" });
//将实体MyStudent插入Student表
}
}
}
/// <summary>
/// 继承了学生表
/// </summary>
public class MyStudent : Student
{
/// <summary>
/// 这两个字段Student表并不存在
/// </summary>
public string appendField { get; set; }
public string appendField2 { get; set; }
}
}

智能提示配置

http://www.cnblogs.com/sunkaixuan/p/5851425.html

多库并行计算功能

 using (CloudClient db = CloudDao.GetInstance())
{
db.PageMaxHandleNumber = ;
using (CommittableTransaction trans = new CommittableTransaction())//启用分布式事务
{ db.Tran = trans; /*** 增、删、改 ***/ //根据配置的百分比,随机插入到某个节点库
var s = new student()
{
createTime = DateTime.Now,
id = Guid.NewGuid(),
name = Guid.NewGuid() + ""
};
//db.Insert<student>(s, false/*false表示不是自增列*/); //数据库设计主键为GUID为佳多库计算不会冲突 ////并发请求所有节点找出这条数据更新
//s.name = "改11";
//db.Update<student>(s, it => it.id == s.id);//根据表达示更新 //db.Update<student, Guid>(s, s.id);//根据主键更新 //db.Update<student, Guid>(s, new Guid[] { s.id });//根据主键数组更新 ////并发请求所有节点找出这条数据删除
//db.Delete<student>(it => it.id == s.id); trans.Commit();
} db.TranDispose(); /*** 使用Taskable实现云计算 ***/ //多线程请求所有数据库节点,获取汇总结果
var taskDataTable = db.Taskable<DataTable>("SELECT max(NUM) FROM STUDENT").Tasks;
foreach (var dr in taskDataTable)//遍历所有节点数据
{
var dt = dr.Result.DataTable;//每个节点的数据 类型为DataTable
var connectionName = dr.Result.ConnectionString;
} //多线程请求所有数据库节点,获取汇总结果
var taskInt = db.Taskable<int>("SELECT max(NUM) FROM STUDENT").Tasks;
foreach (var dr in taskInt)//遍历所有节点数据
{
var dt = dr.Result.Value;//获取单个值
var connectionName = dr.Result.ConnectionString;
} //多线程请求所有数据库节点,获取汇总结果
var taskEntity = db.Taskable<student>("SELECT top 100 * FROM STUDENT").Tasks;
foreach (var dr in taskEntity)//遍历所有节点数据
{
var dt = dr.Result.Entities;//获取实体集合
var connectionName = dr.Result.ConnectionString;
} // //Taskable实现分组查询
// var groupList = db.Taskable<DataTable>("SELECT name,COUNT(*) AS [count],AVG(num) as num FROM STUDENT WHERE ID IS NOT NULL GROUP BY NAME ")
// .Tasks
// .SelectMany(it => it.Result.DataTable.AsEnumerable())
// .Select(dr => new { num = Convert.ToInt32(dr["NUM"]), name = dr["NAME"].ToString(), count = Convert.ToInt32(dr["COUNT"]) })
// .GroupBy(dr => dr.name).Select(dt => new { name = dt.First().name, count = dt.Sum(dtItem => dtItem.count), num = dt.Sum(dtItem => dtItem.num) / dt.Sum(dtItem => dtItem.count) }).ToList(); // //输出结果
// foreach (var it in groupList)
// {
// var num = it.num;
// var name = it.name;
// var count = it.count;
// } // //简化
// var groupList2 = db.Taskable<DataTable>("SELECT NAME,COUNT(*) AS [COUNT],AVG(NUM) as NUM FROM STUDENT WHERE ID IS NOT NULL GROUP BY NAME ")
//.MergeTable()//将结果集合并到一个集合
//.Select(dr => new { num = Convert.ToInt32(dr["NUM"]), name = dr["NAME"].ToString(), count = Convert.ToInt32(dr["COUNT"]) })
//.GroupBy(dr => dr.name).Select(dt => new { name = dt.First().name, count = dt.Sum(dtItem => dtItem.count), num = dt.Sum(dtItem => dtItem.num) / dt.Sum(dtItem => dtItem.count) }).ToList(); // //再简化
// List<V_Student> groupList3 = db.Taskable<V_Student>("SELECT name,COUNT(*) AS [count],AVG(num) as num FROM STUDENT WHERE ID IS NOT NULL GROUP BY NAME ")
//.MergeEntities()//将结果集合并到一个集合
//.GroupBy(dr => dr.name).Select(dt => new V_Student { name = dt.First().name, count = dt.Sum(dtItem => dtItem.count), num = dt.Sum(dtItem => dtItem.num) / dt.Sum(dtItem => dtItem.count) }).ToList(); //更多简化函数
int maxValue = db.Taskable<int>("SELECT max(NUM) FROM STUDENT").Max();//求出所有节点的最大值
int minValue = db.Taskable<int>("SELECT min(NUM) FROM STUDENT").Min();//求出所有节点的最小值
var dataCount = db.Taskable<int>("SELECT count(1) FROM STUDENT").Count();//求出所有节点数据
// var avg = db.TaskableWithCount<int>("SELECT avg(num)", " FROM STUDENT").Avg();
var all = db.Taskable<student>("select * from student where Contains(name,@name)"/*使用contains需要建全文索引*/, new { name = "张三" }).ToList();//获取所有节点name为张三的数据,转为list var dnSingle = DateTime.Now;
var data = db.Taskable<student>("select * from student where id=@id", new { id = id }).ToSingle();//从所有节点中查询一条记录
var timeSingle = (DateTime.Now - dnSingle).TotalSeconds; var dn = DateTime.Now;
//单列排序
// var list = db.TaskableWithPage<student>("id", "select * from student "/*使用contains需要建全文索引*/, 2160, 25, ref pageCount, "num", OrderByType.desc, new { name = "\"*李*\"" });
var time = (DateTime.Now - dn).TotalSeconds; //多组排序 order by num,time
var dn2 = DateTime.Now;
var listMultipleOrderBy = db.TaskableWithPage<student>("id", "select * from student "/*使用contains需要建全文索引*/, , , ref pageCount, new List<OrderByDictionary>() {
new OrderByDictionary(){ OrderByField="num", OrderByType=OrderByType.asc},
// new OrderByDictionary(){ OrderByField="createTime", OrderByType=OrderByType.desc},
// new OrderByDictionary(){ OrderByField="createTime", OrderByType=OrderByType.asc}
}, new { name = "\"*小*\"" });
var time2 = (DateTime.Now - dn2).TotalSeconds; }

多库模式

 /// <summary>
/// 测试类
/// </summary>
public class student
{
public Guid id { get; set; }
public string name { get; set; }
public DateTime createTime { get; set; }
public int num { get; set; }
}
/// <summary>
/// 获取数据库连接对象
/// </summary>
public class CloudDao
{
private CloudDao() { }
public static CloudClient GetInstance()
{
return new CloudClient(new List<CloudConnectionConfig>() {
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c1"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c2"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c3"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c4"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c5"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c6"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c7"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c8"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c9"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c10"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c15"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c16"].ToString(), Rate=},
new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c17"].ToString(), Rate=},
//new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["cy1"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["cy2"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["cy3"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["zq1"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["zq2"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["zq3"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["qp1"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["qp2"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["qp3"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wy1"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wy2"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wy3"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wwf1"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wwf2"].ToString(), Rate=1},
// new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wwf3"].ToString(), Rate=1}, });
}
}

多库配置

3、性能/Performance

OracleSugar ORM框架的诞生,代码开源

 GITHUB下载地址:

MSSQL .NET 4.0+

https://github.com/sunkaixuan/SqlSugar

MSSQL .NET Core 版本

https://github.com/sunkaixuan/ASP_NET_CORE_ORM_SqlSugar

 Sqlite .net4.0+

https://github.com/sunkaixuan/SqliteSugar

MYSQL .NET 4.0+

http://www.cnblogs.com/sunkaixuan/p/5747259.html

ORACLE.NET 4.0+

https://github.com/sunkaixuan/OracleSugar

ORACLE ,MYSQL CORE,SQLITE  CORE

待开发

技术讨论群: 225982985

  

OracleSugar ORM框架的诞生,代码开源的更多相关文章

  1. PHP ORM框架与简单代码实现&lpar;转&rpar;

    对象关系映射(Object Relational Mapping,简称ORM)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单的说,ORM是通过使用描述对象和数据库之间映射的元数据 ...

  2. 【Idea插件】kotlin的orm框架一键生成代码框架

    @font-face { font-family: octicons-link; src: url("data:font/woff;charset=utf-8;base64,d09GRgAB ...

  3. c&num; 轻量级 ORM 框架 之 DBHelper 实现 &lpar;三&rpar;

    周末了比较清闲,把自己的orm框架整理了下,开源了. 已经做出来的东西通常感觉有些简单,一些新手或许听到"框架"一类的词觉得有些"高深",简单来说orm就是把a ...

  4. 各种ORM框架对比(理论篇,欢迎来观摩)

    各种ORM框架对比 目前框架有以下 PetaPoco Dapper.NET Massive Simple.Data Chain PetaPoco 轻量级,以前单文件,目前有维护形成项目级别,适合多个数 ...

  5. 目前的&period;NET&lpar;C&num;&rpar;世界里,主流的ORM框架

    推荐一些常用的asp.net ORM框架 SqlSugar (国内) Dos.ORM (国内) Chloe (国内) StackExchange/Dapper (国外) Entity Framewor ...

  6. &period;NET&lpar;C&num;&rpar;主流的ORM框架

    .NET(C#)主流ORM总揽 SqlSugar (国内) Dos.ORM (国内) Chloe (国内) StackExchange/Dapper (国外) Entity Framework (EF ...

  7. 各种ORM框架对比(理论篇,欢迎来观摩,并且纠正部分错误,防止误区)

    各种ORM框架对比 目前框架有以下 PetaPoco Dapper.NET Massive Simple.Data Chain PetaPoco 轻量级,以前单文件,目前有维护形成项目级别,适合多个数 ...

  8. &period;NET&lpar;C&num;&rpar;有哪些主流的ORM框架,SqlSugar,Dapper,EF还是&period;&period;&period;

    前言 在以前的一篇文章中,为大家分享了<什么是ORM?为什么用ORM?浅析ORM的使用及利弊>.那么,在目前的.NET(C#)的世界里,有哪些主流的ORM,SqlSugar,Dapper, ...

  9. 一行代码调用实现带字段选取+条件判断+排序+分页功能的增强ORM框架

    问题:3行代码 PDF.NET是一个开源的数据开发框架,它的特点是简单.轻量.快速,易上手,而且是一个注释完善的国产开发框架,受到不少朋友的欢迎,也在我们公司的项目中多次使用.但是,PDF.NET比起 ...

随机推荐

  1. SQLite剖析之存储模型

    前言 SQLite作为嵌入式数据库,通常针对的应用的数据量相对于DBMS的数据量小.所以它的存储模型设计得非常简单,总的来说,SQLite把一个数据文件分成若干大小相等的页面,然后以B树的形式来组织这 ...

  2. 使用html5 地理位置技术 和 百度地图api查询当前位置

    使用了  zepto  和 requirejs define(['zepto'],function($){ var geolocation = { init:function(config,onSuc ...

  3. 使用SQLServer同义词和SQL邮件,解决发布订阅中订阅库丢失数据的问题

    最近给客户做了基于SQLServer的发布订阅的“读写分离”功能,但是某些表数据很大,经常发生某几条数据丢失的问题,导致订阅无法继续进行.但是每次发现问题重新做一次发布订阅又非常消耗时间,所以还得根据 ...

  4. SQLMAP实用实例(转)

    sqlmap使用笔记:http://wenku.baidu.com/view/8c507ffcaef8941ea76e055e.html  BT5下使用SQLMAP入侵加脱裤:http://www.m ...

  5. POJ 2986 A Triangle and a Circle

    题意:给定一个三角形,以及一个圆的圆心坐标和半径,求圆和三角形的相交面积. 思路: 用三角剖分,三角形上每个线段都变成这个线段与圆心的三角形,然后算出每个三角形与圆的相交面积,然后根据有向面积的正负累 ...

  6. jquery 实现简单拖拽

    $.fn.drag = function(obj) { var dragging = false; var oDrag = $(obj); oDrag.mousedown(function(e) { ...

  7. springmvc中返回页面,只在iframe中跳转,而不是整个页面,解决方法。

    问题描述:在我写的主页面中用到了iframe,其中在iframe中有一个button点击提交,然后在Controller中返回页面的时候,是在iframe中打开的,而不是整个页面. 最开始我想用aja ...

  8. tk&period;mybatis&period;mapper&period;provider&period;SpecialProvider&period;&lt&semi;init&gt&semi;&lpar;&rpar;

    2017-03-26 23:44:29.192 ERROR 48392 --- [p-nio-80-exec-5] c.t.global.exception.GlobalExHandler : nes ...

  9. &lbrack;Swift&rsqb;LeetCode1025&period; 除数博弈 &vert; Divisor Game

    Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number N o ...

  10. 九大常用排序算法 python

    1.冒泡排序 import random from timewrap import * @cal_time def bubble_sort(li): for i in range(len(li)-1) ...