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

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

 

优点:

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 == 1);
                //查询单条没有记录返回空对象
                var singleOrDefault = db.Queryable<STUDENT>().SingleOrDefault(c => c.ID == 11111111);
                //查询单条没有记录返回空对象
                var single2 = db.Queryable<STUDENT>().Where(c => c.ID == 1).SingleOrDefault();

                //查询第一条
                var first = db.Queryable<STUDENT>().Where(c => c.ID == 1).First();
                var first2 = db.Queryable<STUDENT>().Where(c => c.ID == 1).FirstOrDefault();

                //取10-20条
                var page1 = db.Queryable<STUDENT>().Where(c => c.ID > 10).OrderBy(it => it.ID).Skip(10).Take(20).ToList();

                //上一句的简化写法,同样取10-20条
                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("id>100 ").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<STUDENT, 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<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[] { "5", "2", "3" };
                var intList = intArray.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 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<SexTotal> list9 = db.Queryable<STUDENT>().Where(c => c.ID < 20).GroupBy(it => it.SEX).Select<STUDENT, SexTotal>("SEX,count(*) COUNT").ToList();
                List<SexTotal> list10 = db.Queryable<STUDENT>().Where(c => c.ID < 20).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 == 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<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 > 1)
                .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.NAME)
                .Skip(10)
                .Take(20)
                .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 > 1)  // where s1.id>1
               .Where<STUDENT>(s1 => s1.ID > 0)
               .OrderBy<STUDENT, 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<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() == 1)
                {
                    queryable.Where(it => it.ID == 1);
                }
                else
                {
                    queryable.Where(it => it.ID == 2);
                }
                var listJoin = queryable.ToList();


                //queryable和SqlSugarClient解耦
                var par = new Queryable<STUDENT>().Where(it => it.ID == 1);//声名没有connection对象的Queryable
                par.DB = db;
                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 = "   我 有空格, ";
                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 == 1.ObjToInt()).ToSql();//ObjToInt会将null转转成0
                var r4 = db.Queryable<INSERTTEST>().Where(it => it.ID == 2.ObjToDecimal()).ToSql();
                var r5 = db.Queryable<INSERTTEST>().Where(it => it.ID == 3.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("1")).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 = 1 });
                //转成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 = 1 });

                //多表分页
                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", 1, 10);

                //多表分页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", 1, 10);



                //--------转成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 = 1 });
                var list2 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToJson("*", new { id = 1 });
                var list3 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=:id", JoinType.INNER).SelectToDataTable("*", new { id = 1 });

                //分页
                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", 1, 10, new { id = 1 });
                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", 1, 10, new { id = 1 });
                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", 1, 10, new { id = 1 });


                //--------拼接-----//
                Sqlable sable = db.Sqlable().From<STUDENT>("s").Join<SCHOOL>("l", "s.sch_id", "l.id", JoinType.INNER);
                string name = "a";
                int id = 1;
                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 > 0)
                {
                    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", 1, 20, pars);
View Code

 

 

4、新容器转换 / To new container

 using (SqlSugarClient db = SugarDao.GetInstance())
            {
                var list2 = db.Queryable<STUDENT>().Where(c => c.ID < 10).Select(c => new classNew { NEWID = c.ID, NEWNAME = c.NAME, XX_NAME = c.NAME }).ToList();//不支持匿名类转换,也不建议使用

                var list3 = db.Queryable<STUDENT>().Where(c => c.ID < 10).Select(c => new { newid = c.ID, newname = c.NAME, xx_name = c.NAME }).ToDynamic();//匿名类转换

                var list4 = db.Queryable<STUDENT>().Where(c => c.ID < 10).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 > 1)  // where s1.id>1
                 .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多个order可以  .oderBy().orderby 叠加 
                 .Skip(1)
                 .Take(2)
                 .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 > 1)  // where s1.id>1
                .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多个order可以  .oderBy().orderby 叠加 
                .Skip(1)
                .Take(2)
                .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 > 1)  // where s1.id>1
                .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多个order可以  .oderBy().orderby 叠加 
                .Skip(1)
                .Take(2)
                .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(1, int.MaxValue)
                };

                db.Insert(s); //插入一条记录 (有主键也好,没主键也好,有自增列也好都可以插进去)


                List<STUDENT> list = new List<STUDENT>()
                {
                     new STUDENT()
                {
                     NAME=""+new Random().Next(1,int.MaxValue)
                },
                 new STUDENT()
                {
                     NAME=""+new Random().Next(1,int.MaxValue)
                }
                };

                db.InsertRange(list); //批量插入
            }

 

 

更新/Update

            int id = 11;
using (var db = SugarDao.GetInstance())
            {
                //指定列更新
                db.Update<SCHOOL>(new { name = "蓝翔14" }, it => it.ID == 14);
                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 == id);

   

                //支持字段指定列更新,适合动态权限
                var dic =new Dictionary<string, string>();
                dic.Add("name","第十三条");
                dic.Add("areaId", "1");
                db.Update<SCHOOL,int>(dic, 13);
                db.Update<SCHOOL>(dic, it => it.ID == 13);



                //整个实体更新
                db.Update(new SCHOOL { ID = 16, NAME = "蓝翔16", AREAID=1 });
                db.Update<SCHOOL>(new SCHOOL { ID = id, NAME = "蓝翔18", AREAID=2 }, it => it.ID == 18);
                db.Update<SCHOOL>(new SCHOOL() { ID = 11, NAME = "xx" });

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

                TESTUPDATECOLUMNS updObj = new TESTUPDATECOLUMNS()
                {
                    VGUID = "542b5a27-6984-47c7-a8ee-359e483c8470",
                    NAME = "xx",
                    NAME2 = "xx2",
                    IDENTITYFIELD = 1,
                    CREATETIME = null
                };

                //CreateTime将不会被更新
                db.Update(updObj);
                //以前实现这种更新需要用指定列的方式实现,现在就简单多了。
               
            }

 

 

删除和假删除/Delete And False Delete

using (var db = SugarDao.GetInstance())
            {
                //真删除
                db.Delete<School, int>(10);//注意主键必需为实体类的第一个属性
                db.Delete<School>(it => it.id > 100);
                db.Delete<School, string>(new string[] { "100", "101", "102" });

                //假删除
                //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=1}};
               }
          },
          { "org",()=>{ 
                    return new KeyValueObj(){ Key=" orgId=:orgId" , Value=new{ orgId=1}};
              }
          },
        };
        public static SqlSugarClient GetInstance()
        {
            string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //这里可以动态根据cookies或session实现多库切换
            var reval = new SqlSugarClient(connection);
            reval.SetFilterFilterParas(_filterParas);
            return reval;
        }
    }
}
View Code

 

行列同时过滤 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=1}};
                   }
              },
              { "org",()=>{
                  return new KeyValueObj() { Key = " id=:id", Value = new { id = 2 } };
                  }
              },
            };
        /// <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;
        }
    }

}
View Code

 

 

 

 

 

无参模式/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");
            }
        }
    }
}
View Code

 

 

事务 /Transaction

 using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接
            {
                db.IsNoLock = true;//启用无锁查询
                db.CommandTimeOut = 30000;//设置超时时间
                try
                {
                    db.BeginTran();//开启事务

                    db.CommitTran();//提交事务
                }
                catch (Exception)
                {
                    db.RollbackTran();//回滚事务
                    throw;
                }
            }
事务

 

公开函数 /Common Method

 //ToJoinSqlInVal
            var par = new string[] { "a", "c", "3" };
            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=1});
函数

 

实体生成 /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=1},"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 = 1500;
                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需要建全文索引*/, 5000, 25, 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=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c2"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c3"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c4"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c5"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c6"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c7"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c8"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c9"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c10"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c15"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c16"].ToString(), Rate=1},              
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c17"].ToString(), Rate=1},
                //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

 

 

 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

 

  

posted @ 2016-09-14 12:17  阿妮亚  阅读(9630)  评论(29编辑  收藏  举报