From 0d1df90b5bb6f20702777061427ed229c00769d4 Mon Sep 17 00:00:00 2001 From: sunkaixuan <610262374@qq.com> Date: Fri, 17 May 2019 18:04:18 +0800 Subject: [PATCH] Update PgSql --- Src/Asp.Net/PgSqlTest/Class1.cs | 12 + Src/Asp.Net/PgSqlTest/Config.cs | 15 + Src/Asp.Net/PgSqlTest/Demos/1_Query.cs | 571 ++++++++++++++++++ Src/Asp.Net/PgSqlTest/Demos/2_Update.cs | 87 +++ Src/Asp.Net/PgSqlTest/Demos/3_Insert.cs | 70 +++ Src/Asp.Net/PgSqlTest/Demos/4_Delete.cs | 45 ++ Src/Asp.Net/PgSqlTest/Demos/5_CodeFirst.cs | 59 ++ Src/Asp.Net/PgSqlTest/Demos/5_DbFirst.cs | 72 +++ Src/Asp.Net/PgSqlTest/Demos/6_ComplexModel.cs | 81 +++ Src/Asp.Net/PgSqlTest/Demos/7_Filter.cs | 84 +++ Src/Asp.Net/PgSqlTest/Demos/8_JoinSql.cs | 123 ++++ Src/Asp.Net/PgSqlTest/Demos/9_Aop.cs | 87 +++ Src/Asp.Net/PgSqlTest/Demos/A_MasterSlave.cs | 44 ++ .../PgSqlTest/Demos/B_SharedConnection.cs | 87 +++ .../PgSqlTest/Demos/CS_TeacherStudent.cs | 88 +++ Src/Asp.Net/PgSqlTest/Demos/C_ExtSqlFun.cs | 53 ++ .../PgSqlTest/Demos/D_QueryableView.cs | 33 + Src/Asp.Net/PgSqlTest/Demos/E_Attribute.cs | 43 ++ .../PgSqlTest/Demos/F_VersionValidation.cs | 119 ++++ Src/Asp.Net/PgSqlTest/Demos/G_Mapper.cs | 64 ++ Src/Asp.Net/PgSqlTest/Demos/H_ExtEntity.cs | 58 ++ Src/Asp.Net/PgSqlTest/Demos/H_Queue.cs | 65 ++ .../PgSqlTest/Demos/PerformanceTest.cs | 115 ++++ Src/Asp.Net/PgSqlTest/Demos/Z_DemoBase.cs | 22 + Src/Asp.Net/PgSqlTest/Models/DataTestInfo.cs | 135 +++++ Src/Asp.Net/PgSqlTest/Models/DataTestInfo2.cs | 44 ++ Src/Asp.Net/PgSqlTest/Models/Enum.cs | 22 + Src/Asp.Net/PgSqlTest/Models/School.cs | 18 + Src/Asp.Net/PgSqlTest/Models/Student.cs | 25 + .../PgSqlTest/Models/ViewModelStudent.cs | 26 + Src/Asp.Net/PgSqlTest/PgSqlTest.csproj | 85 +++ Src/Asp.Net/PgSqlTest/Program.cs | 37 ++ .../PgSqlTest/Properties/AssemblyInfo.cs | 36 ++ Src/Asp.Net/SqlSugar.sln | 6 + .../Infrastructure/DependencyManagement.cs | 23 +- 35 files changed, 2549 insertions(+), 5 deletions(-) create mode 100644 Src/Asp.Net/PgSqlTest/Class1.cs create mode 100644 Src/Asp.Net/PgSqlTest/Config.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/1_Query.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/2_Update.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/3_Insert.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/4_Delete.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/5_CodeFirst.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/5_DbFirst.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/6_ComplexModel.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/7_Filter.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/8_JoinSql.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/9_Aop.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/A_MasterSlave.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/B_SharedConnection.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/CS_TeacherStudent.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/C_ExtSqlFun.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/D_QueryableView.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/E_Attribute.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/F_VersionValidation.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/G_Mapper.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/H_ExtEntity.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/H_Queue.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/PerformanceTest.cs create mode 100644 Src/Asp.Net/PgSqlTest/Demos/Z_DemoBase.cs create mode 100644 Src/Asp.Net/PgSqlTest/Models/DataTestInfo.cs create mode 100644 Src/Asp.Net/PgSqlTest/Models/DataTestInfo2.cs create mode 100644 Src/Asp.Net/PgSqlTest/Models/Enum.cs create mode 100644 Src/Asp.Net/PgSqlTest/Models/School.cs create mode 100644 Src/Asp.Net/PgSqlTest/Models/Student.cs create mode 100644 Src/Asp.Net/PgSqlTest/Models/ViewModelStudent.cs create mode 100644 Src/Asp.Net/PgSqlTest/PgSqlTest.csproj create mode 100644 Src/Asp.Net/PgSqlTest/Program.cs create mode 100644 Src/Asp.Net/PgSqlTest/Properties/AssemblyInfo.cs diff --git a/Src/Asp.Net/PgSqlTest/Class1.cs b/Src/Asp.Net/PgSqlTest/Class1.cs new file mode 100644 index 000000000..c882265a9 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PgSqlTest +{ + public class Class1 + { + } +} diff --git a/Src/Asp.Net/PgSqlTest/Config.cs b/Src/Asp.Net/PgSqlTest/Config.cs new file mode 100644 index 000000000..f526fa969 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Config.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Config + { + public static string ConnectionString = "PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=jhl52771;USER ID=postgres"; + public static string ConnectionString2 = "PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=jhl52771;USER ID=postgres"; + public static string ConnectionString3 = "PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=jhl52771;USER ID=postgres"; + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/1_Query.cs b/Src/Asp.Net/PgSqlTest/Demos/1_Query.cs new file mode 100644 index 000000000..d6ce73026 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/1_Query.cs @@ -0,0 +1,571 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Query : DemoBase + { + + public static void Init() + { + Easy(); + Page(); + Where(); + Join(); + Funs(); + Select(); + Ado(); + Group(); + Sqlable(); + Tran(); + StoredProcedure(); + Enum(); + Simple(); + Async(); + Subqueryable(); + SqlQueryable(); + } + + private static void SqlQueryable() + { + var db = GetInstance(); + var list = db.SqlQueryable("select * from student").ToPageList(1, 2); + } + + private static void Subqueryable() + { + var db = GetInstance(); + var i = 0; + + + var sumflat2num = db.Queryable((s1, s2) => + new object[] { JoinType.Left, s1.Id == s2.Id }) + + .Select((s1, s2) => new Student + { Id = SqlFunc.IsNull(SqlFunc.AggregateSum(SqlFunc.IIF(s1.Id ==1, s1.Id, s1.Id * -1)), 0) }) + .First(); + + var getAll11 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Max(s=>s.Id)==i).ToList(); + var getAll12 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Max(s => s.Id) == 1).ToList(); + var getAll7 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Any()).ToList(); + + var getAll9 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Count()==1).ToList(); + + var getAll10 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).OrderBy(s=>s.Id).Select(s=>s.Id) == 1).ToList(); + var getAll14 = db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).OrderByDesc(s => s.Id).Select(s => s.Id) == 1).ToList(); + + var getAll8= db.Queryable().Where(it => SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Where(s=>s.Name==it.Name).NotAny()).ToList(); + + var getAll1 = db.Queryable().Where(it => it.Id == SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Select(s => s.Id)).ToList(); + + var getAll2 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.Id==sc.Id + }) + .Where(st => st.Id == SqlFunc.Subqueryable().Where(s => s.Id == st.Id).Select(s => s.Id)) + .ToList(); + + var getAll3 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.Id==sc.Id + }) + .Select(st => + new + { + name = st.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == st.Id).Select(s => s.Id) + }) + .ToList(); + + var getAll4 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Select(s => s.Id) + }).ToList(); + + var getAll5 = db.Queryable().Select(it => + new Student + { + Name = it.Name, + Id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Select(s => s.Id) + }).ToList(); + + var getAll6 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Sum(s => (int)s.SchoolId) + }).ToList(); + + var getAll66 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Sum(s =>s.SchoolId.Value) + }).ToList(); + + var getAll666 = db.Queryable().Select(it => + new + { + name = it.Name, + id = SqlFunc.Subqueryable().Where(s => s.Id == it.Id).Min(s => s.Id) + }).ToList(); + + } + + private static void Async() + { + var db = GetInstance(); + var list = db.Queryable().Where(it => it.Id == 1).SingleAsync(); + list.Wait(); + + var list2 = db.Queryable().SingleAsync(it => it.Id == 1); + list2.Wait(); + + var list3 = db.Queryable().Where(it => it.Id == 1).ToListAsync(); + list3.Wait(); + + var list4 = db.Queryable().Where(it => it.Id == 1).ToPageListAsync(1, 2); + list4.Wait(); + } + + private static void Simple() + { + //SqlSugarClient + var db = GetInstance(); + var student1 = db.Queryable().InSingle(1); + + //get SimpleClient + var sdb = db.GetSimpleClient(); + var student2 = sdb.GetById(1); + sdb.DeleteById(1); + sdb.Insert(new Student() { Name = "xx" }); + sdb.Update(it => new Student { Name = "newvalue" }, it => it.Id == 1);//only update name where id=1 + sdb.Update(new Student() { Name = "newavalue", Id = 1 });//update all where id=1 + + //SimpleClient Get SqlSugarClient + var student3 = sdb.FullClient.Queryable().InSingle(1); + + } + + private static void StoredProcedure() + { + + } + private static void Tran() + { + var db = GetInstance(); + var x = db.Insertable(new Student() { CreateTime = DateTime.Now, Name = "tran" }).ExecuteCommand(); + //1. no result + var result = db.Ado.UseTran(() => + { + + var beginCount = db.Queryable().ToList(); + db.Ado.ExecuteCommand("delete student"); + var endCount = db.Queryable().Count(); + throw new Exception("error haha"); + }); + var count = db.Queryable().Count(); + + //2 has result + var result2 = db.Ado.UseTran>(() => + { + return db.Queryable().ToList(); + }); + + //3 use try + try + { + db.Ado.BeginTran(); + + db.Ado.CommitTran(); + } + catch (Exception) + { + db.Ado.RollbackTran(); + throw; + } + + + + //async tran + var asyncResult = db.Ado.UseTranAsync(() => + { + + var beginCount = db.Queryable().ToList(); + db.Ado.ExecuteCommand("delete student"); + var endCount = db.Queryable().Count(); + throw new Exception("error haha"); + }); + asyncResult.Wait(); + var asyncCount = db.Queryable().Count(); + + //async + var asyncResult2 = db.Ado.UseTranAsync>(() => + { + return db.Queryable().ToList(); + }); + asyncResult2.Wait(); + } + private static void Group() + { + var db = GetInstance(); + var list = db.Queryable() + .GroupBy(it => it.Name) + .GroupBy(it => it.Id).Having(it => SqlFunc.AggregateAvg(it.Id) > 0) + .Select(it => new { idAvg = SqlFunc.AggregateAvg(it.Id), name = it.Name }).ToList(); + + + var list2 = db.Queryable() + .GroupBy(it => new { it.Id, it.Name }).Having(it => SqlFunc.AggregateAvg(it.Id) > 0) + .Select(it => new { idAvg = SqlFunc.AggregateAvg(it.Id), name = it.Name }).ToList(); + //SQL: + //SELECT AVG([Id]) AS[idAvg], [Name] AS[name] FROM[Student] GROUP BY[Name],[Id] HAVING(AVG([Id]) > 0 ) + + // group id,name take first + var list3 = db.Queryable() + .PartitionBy(it => new { it.Id, it.Name }).Take(1).ToList(); + var list31 = db.Queryable() + .PartitionBy(it => new { it.Id, it.Name }).Take(1).Count(); + + int count = 0; + + var list4 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .PartitionBy(st => new { st.Name }).Take(2).OrderBy(st => st.Id, OrderByType.Desc).Select(st => st).ToPageList(1, 1000, ref count); + + //SqlFunc.AggregateSum(object thisValue) + //SqlFunc.AggregateAvg(TResult thisValue) + //SqlFunc.AggregateMin(object thisValue) + //SqlFunc.AggregateMax(object thisValue) + //SqlFunc.AggregateCount(object thisValue) + } + private static void Ado() + { + var db = GetInstance(); + db.Ado.BeginTran(); + var t1 = db.Ado.SqlQuery("select 'a'"); + var t2 = db.Ado.GetInt("select 1"); + var t3 = db.Ado.GetDataTable("select 1 as id"); + db.Ado.CommitTran(); + var t11 = db.Ado.SqlQuery("select * from student"); + //more + //db.Ado.GetXXX... + } + public static void Easy() + { + var db = GetInstance(); + var getAll22 = db.Queryable().ToDataTable(); + var getAll220 = db.Ado.GetDataSetAll("select 1"); + var getAll22222 = db.Queryable().Where(it => it.Id == 1).ToSql(); + var dbTime = db.GetDate(); + var getAll = db.Queryable().Select("*").ToList(); + var getAll2 = db.Queryable().ToList(); + var getRandomList = db.Queryable().OrderBy(it => SqlFunc.GetRandom()).ToList(); + var getAllOrder = db.Queryable().OrderBy(it => it.Id).OrderBy(it => it.Name, OrderByType.Desc).ToList(); + var getId = db.Queryable().Select(it => it.Id).ToList(); + var getNew = db.Queryable().Where(it => it.Id == 1).Select(it => new { id = SqlFunc.IIF(it.Id == 0, 1, it.Id), it.Name, it.SchoolId }).ToList(); + var getAllNoLock = db.Queryable().With(SqlWith.NoLock).ToList(); + var getByPrimaryKey = db.Queryable().InSingle(2); + var getSingleOrDefault = db.Queryable().Where(it => it.Id == 1).Single(); + var getFirstOrDefault = db.Queryable().First(); + var getByWhere = db.Queryable().Where(it => it.Id == 1 || it.Name == "a").ToList(); + var getByWhere2 = db.Queryable().Where(it => it.Id ==DateTime.Now.Year).ToList(); + var getByFuns = db.Queryable().Where(it => SqlFunc.IsNullOrEmpty(it.Name)).ToList(); + var sum = db.Queryable().Select(it => it.SchoolId).ToList(); + var sum2 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Sum((st, sc) => sc.Id); + var isAny = db.Queryable().Where(it => it.Id == -1).Any(); + var isAny2 = db.Queryable().Any(it => it.Id == -1); + var count = db.Queryable().Count(it => it.Id > 0); + // var date = db.Queryable().Where(it => it.CreateTime.Value.Date == DateTime.Now.Date).ToList(); + var getListByRename = db.Queryable().AS("Student").ToList(); + var in1 = db.Queryable().In(it => it.Id, new int[] { 1, 2, 3 }).ToList(); + var in2 = db.Queryable().In(new int[] { 1, 2, 3 }).ToList(); + int[] array = new int[] { 1, 2 }; + var in3 = db.Queryable().Where(it => SqlFunc.ContainsArray(array, it.Id)).ToList(); + var group = db.Queryable().GroupBy(it => it.Id) + .Having(it => SqlFunc.AggregateCount(it.Id) > 10) + .Select(it => new { id = SqlFunc.AggregateCount(it.Id) }).ToList(); + + var between = db.Queryable().Where(it => SqlFunc.Between(it.Id, 1, 20)).ToList(); + + // var getTodayList = db.Queryable().Where(it => SqlFunc.DateIsSame(it.CreateTime, DateTime.Now)).ToList(); + + var joinSql = db.Queryable("student", "s").OrderBy("id").Select("id,name").ToPageList(1, 2); + + // var getDay1List = db.Queryable().Where(it => it.CreateTime.Value.Hour == 1).ToList(); + //var getDateAdd = db.Queryable().Where(it => it.CreateTime.Value.AddDays(1) == DateTime.Now).ToList(); + //var getDateIsSame = db.Queryable().Where(it => SqlFunc.DateIsSame(DateTime.Now, DateTime.Now, DateType.Hour)).ToList(); + + var getSqlList = db.Queryable().AS("(select * from student) t").ToList(); + + + var getUnionAllList = db.UnionAll(db.Queryable().Where(it => it.Id == 1), db.Queryable().Where(it => it.Id == 2)).ToList(); + + var getUnionAllList2 = db.UnionAll(db.Queryable(), db.Queryable()).ToList(); + + //var getUnionAllList3= db.UnionAll(db.Queryable() + // .Select(it => new Student { Id =SqlFunc.ToInt32(1) ,Name=SqlFunc.ToString("2"), SchoolId = Convert.ToInt32(3) }) + // , db.Queryable() + // .Select(it => new Student { Id = SqlFunc.ToInt32(11) , Name = SqlFunc.ToString("22") , SchoolId=Convert.ToInt32(33)})) + // .Select(it=>new Student() { Id=SqlFunc.ToInt32(111), Name = SqlFunc.ToString("222") }).ToList(); + + //var test1 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Where(st=>st.CreateTime>SqlFunc.GetDate()).Select((st, sc) => SqlFunc.ToInt64(sc.Id)).ToList(); + var test2 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .Where(st => + SqlFunc.IF(st.Id > 1) + .Return(st.Id) + .ElseIF(st.Id == 1) + .Return(st.SchoolId).End(st.Id) == 1).Select(st=>st).ToList(); + var test3 = db.Queryable().Select(it => it.Bool1).ToSql(); + var test4 = db.Queryable().Select(it => new { b=it.Bool1 }).ToSql(); + DateTime? result = DateTime.Now; + var test5 = db.Queryable().Where(it=>it.CreateTime> result.Value.Date).ToList(); + } + public static void Page() + { + var db = GetInstance(); + var pageIndex = 1; + var pageSize = 2; + var totalCount = 0; + //page + var page = db.Queryable().OrderBy(it => it.Id).ToPageList(pageIndex, pageSize, ref totalCount); + + //page join + var pageJoin = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).ToPageList(pageIndex, pageSize, ref totalCount); + + //top 5 + var top5 = db.Queryable().Take(5).ToList(); + + //skip5 + var skip5 = db.Queryable().Skip(5).ToList(); + } + public static void Where() + { + var db = GetInstance(); + //join + var list = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Where((st, sc) => sc.Id == 1) + .Where((st, sc) => st.Id == 1) + .Where((st, sc) => st.Id == 1 && sc.Id == 2).ToList(); + + //SELECT [st].[Id],[st].[SchoolId],[st].[Name],[st].[CreateTime] FROM [Student] st + //Left JOIN School sc ON ( [st].[SchoolId] = [sc].[Id] ) + //WHERE ( [sc].[Id] = @Id0 ) AND ( [st].[Id] = @Id1 ) AND (( [st].[Id] = @Id2 ) AND ( [sc].[Id] = @Id3 )) + + + //Where If + string name = null; + string name2 = "sunkaixuan"; + var list2 = db.Queryable() + .WhereIF(!string.IsNullOrEmpty(name), it => it.Name == name) + .WhereIF(!string.IsNullOrEmpty(name2), it => it.Name == name2).ToList(); + + + + //join + var list3 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .WhereIF(false, (st, sc) => sc.Id == 1) + .WhereIF(false, (st, sc) => st.Id == 1).ToList(); + + + var list4 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Select((st, sc) => new { id = st.Id, school = sc }).ToList(); + + + var list5 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).AS("STUDENT").AS("SCHOOL") +.Select((st, sc) => new { id = st.Id, school = sc }).ToList(); + + + var list6 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).AS("STUDENT").AS("SCHOOL") +.Select((st, sc) => new { id = st.Id, school = sc }).ToList(); + } + public static void Join() + { + var db = GetInstance(); + //join 2 + var list = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Where(st => st.Name == "jack").ToList(); + + //join 3 + var list2 = db.Queryable((st, sc, st2) => new object[] { + JoinType.Left,st.SchoolId==sc.Id, + JoinType.Left,st.SchoolId==st2.Id + }) + .Where((st, sc, st2) => st2.Id == 1 || sc.Id == 1 || st.Id == 1).ToList(); + + //join return List + var list3 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).Select((st, sc) => new ViewModelStudent { Name = st.Name, SchoolId = sc.Id }).ToList(); + + //join Order By (order by st.id desc,sc.id desc) + var list4 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .OrderBy(st => st.Id, OrderByType.Desc) + .OrderBy((st, sc) => sc.Id, OrderByType.Desc) + .Select((st, sc) => new ViewModelStudent { Name = st.Name, SchoolId = sc.Id }).ToList(); + + + //join 2 + var list4_1 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id&& st.Name == "jack" + }).ToList(); + + + //The simple use of Join 2 table + var list5 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Select((st, sc) => new { st.Name, st.Id, schoolName = sc.Name }).ToList(); + + //join 3 table + var list6 = db.Queryable((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id) + .Select((st, sc, sc2) => new { st.Name, st.Id, schoolName = sc.Name, schoolName2 = sc2.Name }).ToList(); + + //join 3 table page + var list7 = db.Queryable((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id) + .Select((st, sc, sc2) => new { st.Name, st.Id, schoolName = sc.Name, schoolName2 = sc2.Name }).ToPageList(1, 2); + + //join 3 table page + var list8 = db.Queryable((st, sc, sc2) => st.SchoolId == sc.Id && sc.Id == sc2.Id) + .OrderBy(st => st.Id) + .Select((st, sc, sc2) => new { st.Name, st.Id, schoolName = sc.Name, schoolName2 = sc2.Name }).ToPageList(1, 2); + + //In + var list9 = db.Queryable("it") + .OrderBy(it => it.Id) + .In(it => it.Id, db.Queryable().Where("it.id=schoolId").Select(it => it.Id)) + .ToList(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] it WHERE [ID] + //IN (SELECT [Id] FROM [School] WHERE it.id=schoolId ) ORDER BY [ID] ASC + + var list10 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .In(st => st.Name, db.Queryable("sc2").Where("id=st.schoolid").Select(it => it.Name)) + .OrderBy(st => st.Id) + .Select(st => st) + .ToList(); + //SELECT st.* FROM [STudent] st ,[School] sc WHERE ( [st].[SchoolId] = [sc].[Id] ) AND [st].[Name] + //IN (SELECT [Name] FROM [School] sc2 WHERE id=st.schoolid ) ORDER BY [st].[ID] ASC + + var list11 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .In(st => st.Name, db.Queryable("sc2").Where(it => it.Id == 1).Where("id=st.schoolid").Select(it => it.Name)) + .OrderBy(st => st.Id) + .Select(st => st) + .ToList(); + + var subquery = db.Queryable().Where(it => it.Id == 1); + var subquery2 = db.Queryable(); + db.Queryable(subquery, subquery2, (st1, st2) => st1.Id == st2.Id).Select((st1,st2)=>new { + id=st1.Id, + name=st2.Name + }).ToList(); + } + public static void Funs() + { + var db = GetInstance(); + var t1 = db.Queryable().Where(it => SqlFunc.ToLower(it.Name) == SqlFunc.ToLower("JACK")).ToList(); + var t2 = db.Queryable().Where(it => SqlFunc.IsNull(it.Name,"nullvalue")=="nullvalue").ToList(); + var t3 = db.Queryable().Where(it => SqlFunc.MergeString("a",it.Name) == "nullvalue").ToList(); + //SELECT [Id],[SchoolId],[Name],[CreateTime] FROM [Student] WHERE ((LOWER([Name])) = (LOWER(@MethodConst0)) ) + + /***More Functions***/ + //SqlFunc.IsNullOrEmpty(object thisValue) + //SqlFunc.ToLower(object thisValue) + //SqlFunc.string ToUpper(object thisValue) + //SqlFunc.string Trim(object thisValue) + //SqlFunc.bool Contains(string thisValue, string parameterValue) + //SqlFunc.ContainsArray(object[] thisValue, string parameterValue) + //SqlFunc.StartsWith(object thisValue, string parameterValue) + //SqlFunc.EndsWith(object thisValue, string parameterValue) + //SqlFunc.Equals(object thisValue, object parameterValue) + //SqlFunc.DateIsSame(DateTime date1, DateTime date2) + //SqlFunc.DateIsSame(DateTime date1, DateTime date2, DateType dataType) + //SqlFunc.DateAdd(DateTime date, int addValue, DateType millisecond) + //SqlFunc.DateAdd(DateTime date, int addValue) + //SqlFunc.DateValue(DateTime date, DateType dataType) + //SqlFunc.Between(object value, object start, object end) + //SqlFunc.ToInt32(object value) + //SqlFunc.ToInt64(object value) + //SqlFunc.ToDate(object value) + //SqlFunc.ToString(object value) + //SqlFunc.ToDecimal(object value) + //SqlFunc.ToGuid(object value) + //SqlFunc.ToDouble(object value) + //SqlFunc.ToBool(object value) + //SqlFunc.Substring(object value, int index, int length) + //SqlFunc.Replace(object value, string oldChar, string newChar) + //SqlFunc.Length(object value) { throw new NotImplementedException(); } + //SqlFunc.AggregateSum(object thisValue) + //SqlFunc.AggregateAvg(TResult thisValue) + //SqlFunc.AggregateMin(object thisValue) + //SqlFunc.AggregateMax(object thisValue) + //SqlFunc.AggregateCount(object thisValue) + } + public static void Select() + { + var db = GetInstance(); + db.IgnoreColumns.Add("TestId", "Student"); + var s1 = db.Queryable().Where(it => it.Id == 136915).Single(); + var s2 = db.Queryable().Select(it => new { id = it.Id, w = new { x = it } }).ToList(); + var s3 = db.Queryable().Select(it => new { newid = it.Id }).ToList(); + var s4 = db.Queryable().Select(it => new { newid = it.Id, obj = it }).ToList(); + var s41 = db.Queryable().Select("*").ToList(); + var s5 = db.Queryable().Select(it => new ViewModelStudent2 { Student = it, Name = it.Name }).ToList(); + var s6 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .OrderBy(st => st.Id, OrderByType.Desc) + .OrderBy((st, sc) => sc.Id, OrderByType.Desc) + .Select((st, sc) => new { Name = st.Name, SchoolId = sc.Id }).ToList(); + + + var s7 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).Select((st, sc) => sc).ToList(); + + var s8 = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .OrderBy((st, sc) => st.SchoolId) + .Select((st, sc) => sc) + .Take(1).ToList(); + + var s9 = db.Queryable().Select(it=>new Student() { Id=it.Id, TestId=1, Name=it.Name, CreateTime=it.CreateTime }).First(); + var s10 = db.Queryable().Select(it => new Student() { Id = it.Id}).First(); + + //auto fill + var s11 = db.Queryable((st,sc)=>st.SchoolId==sc.Id).Select().ToList(); + } + private static void Sqlable() + { + var db = GetInstance(); + var join3 = db.Queryable("Student", "st") + .AddJoinInfo("School", "sh", "sh.id=st.schoolid") + .Where("st.id>@id") + .AddParameters(new { id = 1 }) + .Select("st.*").ToList(); + //SELECT st.* FROM [Student] st Left JOIN School sh ON sh.id=st.schoolid WHERE st.id>@id + } + private static void Enum() + { + var db = GetInstance(); + var list = db.Queryable().AS("Student").Where(it => it.SchoolId == SchoolEnum.HarvardUniversity).ToList(); + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/2_Update.cs b/Src/Asp.Net/PgSqlTest/Demos/2_Update.cs new file mode 100644 index 000000000..43fabf06a --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/2_Update.cs @@ -0,0 +1,87 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Update : DemoBase + { + public static void Init() + { + var db = GetInstance(); + var updateObj = new Student() { Id = 1, Name = "jack", SchoolId = 0, CreateTime = Convert.ToDateTime("2017-05-21 09:56:12.610") }; + var updateObjs = new List() { updateObj, new Student() { Id = 2, Name = "sun", SchoolId = 0 } }.ToArray(); + db.IgnoreColumns.Add("TestId", "Student"); + //db.MappingColumns.Add("id","dbid", "Student"); + + + //update reutrn Update Count + var t1 = db.Updateable(updateObj).ExecuteCommand(); + + //Only update Name + var t3 = db.Updateable(updateObj).UpdateColumns(it => new { it.Name }).ExecuteCommand(); + var t3_1 = db.Updateable(updateObj).UpdateColumns(it => it == "Name").ExecuteCommand(); + + + //Ignore Name and TestId + var t4 = db.Updateable(updateObj).IgnoreColumns(it => new { it.Name, it.TestId }).ExecuteCommand(); + + //Ignore Name and TestId + var t5 = db.Updateable(updateObj).IgnoreColumns(it => it == "Name" || it == "TestId").With(SqlWith.UpdLock).ExecuteCommand(); + + + //Use Lock + var t6 = db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand(); + + //update List + var t7 = db.Updateable(updateObjs).ExecuteCommand(); + + //Re Set Value + var t8 = db.Updateable(updateObj) + .ReSetValue(it => it.Name=="xx").ExecuteCommand(); + + //Where By Expression + var t9 = db.Updateable(updateObj).Where(it => it.Id == 1).ExecuteCommand(); + + //Update By Expression Where By Expression + var t10 = db.Updateable() + .UpdateColumns(it => new Student() { Name = "a", CreateTime = DateTime.Now }) + .Where(it => it.Id == 11).ExecuteCommand(); + + //Rename + db.Updateable().AS("Student").UpdateColumns(it => new School() { Name = "jack" }).Where(it => it.Id == 1).ExecuteCommand(); + //Update Student set Name='jack' Where Id=1 + + //Column is null no update + db.Updateable(updateObj).Where(true).ExecuteCommand(); + + //sql + db.Updateable(updateObj).Where("id=@x",new { x=1}).ExecuteCommand(); + db.Updateable(updateObj).Where("id","=",1).ExecuteCommand(); + var t12 = db.Updateable().AS("Student").UpdateColumns(it => new School() { Name = "jack" }).Where(it => it.Id == 1).ExecuteCommandAsync(); + t12.Wait(); + + //update one columns + var count = db.Updateable().UpdateColumns(it => it.SchoolId == it.SchoolId).Where(it => it.Id == it.Id+1).ExecuteCommand(); + + var count1 = db.Updateable() + .UpdateColumnsIF(false,it => it.SchoolId == it.SchoolId)//ignore + .UpdateColumnsIF(true, it => it.SchoolId == 2).//ok + Where(it => it.Id == it.Id + 1).ExecuteCommand(); + + + //update one columns + var count2 = db.Updateable().UpdateColumns(it => it.SchoolId == it.SchoolId+1).Where(it => it.Id == it.Id + 1).ExecuteCommand(); + + var dt = new Dictionary(); + dt.Add("id", 1); + dt.Add("name", null); + dt.Add("createTime", DateTime.Now); + var t66 = db.Updateable(dt).AS("student").With(SqlWith.UpdLock).ExecuteCommand(); + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/3_Insert.cs b/Src/Asp.Net/PgSqlTest/Demos/3_Insert.cs new file mode 100644 index 000000000..82b9b93d3 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/3_Insert.cs @@ -0,0 +1,70 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Insert:DemoBase + { + public static void Init() + { + var db = GetInstance(); + db.IgnoreColumns.Add("TestId", "Student"); + + var insertObj = new Student() { Name = "jack", CreateTime = Convert.ToDateTime("2010-1-1"), SchoolId = 1 }; + + //Insert reutrn Insert Count + var t2 = db.Insertable(insertObj).ExecuteCommand(); + + //Insert reutrn Identity Value + var t3 = db.Insertable(insertObj).ExecuteReturnIdentity(); + + //Insert reutrn Identity Value + var t31 = db.Insertable(insertObj).ExecuteReturnEntity(); + + //Only insert Name and SchoolId + var t4 = db.Insertable(insertObj).InsertColumns(it => new { it.Name, it.SchoolId }).ExecuteReturnIdentity(); + var t4_1 = db.Insertable(insertObj).InsertColumns(it => it=="Name"||it== "SchoolId").ExecuteReturnIdentity(); + + + //Ignore TestId + var t5 = db.Insertable(insertObj).IgnoreColumns(it => new { it.Name, it.TestId }).ExecuteReturnIdentity(); + + + //Ignore TestId + var t6 = db.Insertable(insertObj).IgnoreColumns(it => it == "Name" || it == "TestId").ExecuteReturnIdentity(); + + + //Use Lock + var t8 = db.Insertable(insertObj).With(SqlWith.UpdLock).ExecuteCommand(); + + + var insertObj2 = new Student() { Name = null, CreateTime = Convert.ToDateTime("2010-1-1") }; + var t9 = db.Insertable(insertObj2).Where(true/* Is insert null */, false/*off identity*/).ExecuteCommand(); + + //Insert List + var insertObjs = new List(); + for (int i = 0; i < 1000; i++) + { + insertObjs.Add(new Student() { Name = "name" + i }); + } + var t10 = db.Insertable(insertObjs.ToArray()).InsertColumns(it => new { it.Name }).ExecuteCommand(); + + var t11 = db.Insertable(insertObjs.ToArray()).ExecuteCommand(); + + + var t12 = db.Insertable(insertObj).IgnoreColumns(it => it == "Name" || it == "TestId").ExecuteReturnIdentityAsync(); + t12.Wait(); + + + var dt = new Dictionary(); + dt.Add("name", "1"); + dt.Add("CreateTime", DateTime.Now); + var t66 = db.Insertable(dt).AS("student").ExecuteCommand(); + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/4_Delete.cs b/Src/Asp.Net/PgSqlTest/Demos/4_Delete.cs new file mode 100644 index 000000000..5ca74d226 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/4_Delete.cs @@ -0,0 +1,45 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Demo +{ + public class Delete:DemoBase + { + public static void Init() + { + var db = GetInstance(); + //by entity + var t1 = db.Deleteable().Where(new Student() { Id = 1 }).ExecuteCommand(); + + //use lock + var t2 = db.Deleteable().With(SqlWith.RowLock).ExecuteCommand(); + + + //by primary key + var t3 = db.Deleteable().In(1).ExecuteCommand(); + + //by primary key array + var t4 = db.Deleteable().In(new int[] { 1, 2 }).ExecuteCommand(); + var t41 = db.Deleteable().In(new int[] { 1, 2 }.Select(it=>it)).ExecuteCommand(); + var t42 = db.Deleteable().In(new int[] { 1, 2 }.AsEnumerable()).ExecuteCommand(); + + + //by exp key array + var t44 = db.Deleteable().In(it=>it.SchoolId,new int[] { 1, 2 }).ExecuteCommand(); + var t441 = db.Deleteable().In(it => it.SchoolId,new int[] { 1, 2 }.Select(it => it)).ExecuteCommand(); + var t442 = db.Deleteable().In(it => it.SchoolId,new int[] { 1, 2 }.AsEnumerable()).ExecuteCommand(); + var t443 = db.Deleteable().In(it => it.SchoolId, new int[] { 1, 2 }.ToList()).ExecuteCommand(); + + //by expression id>1 and id==1 + var t5 = db.Deleteable().Where(it => it.Id > 1).Where(it => it.Id == 1).ExecuteCommand(); + + var t6 = db.Deleteable().AS("student").Where(it => it.Id > 1).Where(it => it.Id == 1).ExecuteCommandAsync(); + t6.Wait(); + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/5_CodeFirst.cs b/Src/Asp.Net/PgSqlTest/Demos/5_CodeFirst.cs new file mode 100644 index 000000000..ce21adb4c --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/5_CodeFirst.cs @@ -0,0 +1,59 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + [SugarTable("CodeTable", " table CodeTable")] + public class CodeTable + { + + + [SugarColumn(IsNullable =false ,IsPrimaryKey =true,IsIdentity =true,ColumnDescription ="XXhaha primary key!!")] + public int Id { get; set; } + [SugarColumn(Length = 21,OldColumnName = "Name2")] + public string Name{ get; set; } + public string IsOk { get; set; } + public Guid Guid { get; set; } + [SugarColumn(ColumnDataType ="int")] + public decimal Decimal { get; set; } + [SugarColumn(IsNullable = true)] + public DateTime? DateTime { get; set; } + [SugarColumn(IsNullable = true,OldColumnName = "Dob")] + public double? Dob2 { get; set; } + [SugarColumn(Length =11000)] + public string A1 { get; set; } + [SugarColumn(Length = 18,DecimalDigits=2)] + public decimal Dec { get; set; } + } + public class CodeTable2 { + public int Id { get; set; } + public string Name { get; set; } + [SugarColumn(IsIgnore =true)] + public string TestId { get; set; } + } + public class CodeFirst : DemoBase + { + public static void Init() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.PostgreSQL, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute + }); + + db.CodeFirst.SetStringDefaultLength(30).InitTables(typeof(Student), typeof(School)); + + //Backup table + //db.CodeFirst.BackupTable().InitTables(typeof(CodeTable),typeof(CodeTable2)); + + //No backup table + db.CodeFirst.SetStringDefaultLength(10).InitTables(typeof(CodeTable),typeof(CodeTable2)); + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/5_DbFirst.cs b/Src/Asp.Net/PgSqlTest/Demos/5_DbFirst.cs new file mode 100644 index 000000000..44589fe13 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/5_DbFirst.cs @@ -0,0 +1,72 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class DbFirst : DemoBase + { + public static void Init() + { + var db = GetInstance(); + //Create all class + db.DbFirst.CreateClassFile("c:\\PgDemo\\1"); + + //Create student calsss + db.DbFirst.Where("Student").CreateClassFile("c:\\PgDemo\\2"); + //Where(array) + + //Mapping name + db.MappingTables.Add("ClassStudent", "Student"); + db.MappingColumns.Add("NewId", "Id", "ClassStudent"); + db.DbFirst.Where("Student").CreateClassFile("c:\\PgDemo\\3"); + + //Remove mapping + db.MappingTables.Clear(); + + //Create class with default value + db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\PgDemo\\4", "Demo.Models"); + + + //Mapping and Attribute + db.MappingTables.Add("ClassStudent", "Student"); + db.MappingColumns.Add("NewId", "Id", "ClassStudent"); + db.DbFirst.IsCreateAttribute().Where("Student").CreateClassFile("c:\\PgDemo\\5"); + + + //Remove mapping + db.MappingTables.Clear(); + db.MappingColumns.Clear(); + + //Custom format,Change old to new + db.DbFirst. + SettingClassTemplate(old => + { + return old; + }) + .SettingNamespaceTemplate(old => + { + return old; + }) + .SettingPropertyDescriptionTemplate(old => + { + return @" /// + /// Desc_New:{PropertyDescription} + /// Default_New:{DefaultValue} + /// Nullable_New:{IsNullable} + /// "; + }) + .SettingPropertyTemplate(old => + { + return old; + }) + .SettingConstructorTemplate(old => + { + return old; + }) + .CreateClassFile("c:\\PgDemo\\6"); + } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/PgSqlTest/Demos/6_ComplexModel.cs b/Src/Asp.Net/PgSqlTest/Demos/6_ComplexModel.cs new file mode 100644 index 000000000..b5eecd86c --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/6_ComplexModel.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SqlSugar; +using OrmTest.Demo; + +namespace OrmTest.Demo +{ + public class ComplexModel : DemoBase + { + public static void Init() + { + var db = GetInstance(); + db.Insertable(new CMStudent() { SchoolId = 1, Name = "xx1" }).ExecuteCommand(); + var students = db.Queryable().ToList(); + if (students != null) + { + foreach (var item in students) + { + Console.WriteLine(item.SchoolName); + if (item.SchoolSingle != null) + { + Console.WriteLine(item.SchoolSingle.Name); + } + if (item.SchoolList != null) + { + Console.WriteLine(item.SchoolList.Count); + } + } + } + + db.Insertable(new CMStudent() { Name="xx" }).ExecuteCommand(); + } + } + + [SugarTable("Student")] + public class CMStudent : ModelContext + { + public int Id { get; set; } + public string Name { get; set; } + public int SchoolId { get; set; } + + [SugarColumn(IsIgnore = true)] + public string SchoolName + { + get + { + if (this.SchoolSingle != null) + return this.SchoolSingle.Name; + else + return null; + } + } + + [SugarColumn(IsIgnore = true)] + public CMSchool SchoolSingle + { + get + { + return base.CreateMapping().Single(it => it.Id == this.SchoolId); + } + } + + [SugarColumn(IsIgnore = true)] + public List SchoolList + { + get + { + return base.CreateMapping().Where(it => it.Id == this.SchoolId).ToList(); + } + } + } + + [SugarTable("School")] + public class CMSchool + { + public int Id { get; set; } + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/PgSqlTest/Demos/7_Filter.cs b/Src/Asp.Net/PgSqlTest/Demos/7_Filter.cs new file mode 100644 index 000000000..6f42fba06 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/7_Filter.cs @@ -0,0 +1,84 @@ +using OrmTest.Demo; +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class Filter : DemoBase + { + public static void Init() + { + + + //gobal filter + var db = GetInstance1(); + + var sql = db.Queryable().ToSql(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] WHERE isDelete=0 + + var sql2 = db.Queryable((f, s) => new object[] { JoinType.Left, f.SchoolId == s.Id }).ToSql(); + //SELECT[f].[ID],[f].[SchoolId],[f].[Name],[f].[CreateTime] + //FROM[STudent] f Left JOIN School s ON([f].[SchoolId] = [s].[Id]) WHERE f.isDelete=0 + + + //Specify name filter + var sql3 = db.Queryable().Filter("query1").ToSql(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] WHERE WHERE id>@id AND isDelete=0 + + + //Specify key filter and disabled global filter + string key = "query1"; + var sql4 = db.Queryable().Filter(key,true).ToSql(); + //SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] WHERE WHERE id>@id + + var sql5 = db.Ado.GetInt("select {0}"); + //select 1 + } + + public static SqlSugarClient GetInstance1() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true }); + db.QueryFilter + .Add(new SqlFilterItem() + { + FilterValue = filterDb => + { + return new SqlFilterResult() { Sql = " isDelete=0" }; + }, + IsJoinQuery = false + }).Add(new SqlFilterItem() + { + FilterValue = filterDb => + { + return new SqlFilterResult() { Sql = " f.isDelete=0" }; + }, + IsJoinQuery = true + }) + .Add(new SqlFilterItem() + { + FilterName = "query1", + FilterValue = filterDb => + { + return new SqlFilterResult() { Sql = " id>@id", Parameters = new { id = 1 } }; + }, + IsJoinQuery = false + }); + + //Processing prior to execution of SQL + db.Aop.OnExecutingChangeSql = (sql, par) => + { + if (sql.Contains("{0}")) + { + sql = string.Format(sql, "1"); + } + return new KeyValuePair(sql,par); + }; + return db; + } + } + +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/8_JoinSql.cs b/Src/Asp.Net/PgSqlTest/Demos/8_JoinSql.cs new file mode 100644 index 000000000..8107f72c6 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/8_JoinSql.cs @@ -0,0 +1,123 @@ +using OrmTest.Demo; +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + /// + /// Secure string operations + /// + public class JoinSql : DemoBase + { + public static void Init() + { + Where(); + OrderBy(); + SelectMerge(); + ConditionalModel(); + JoinExp(); + Clone(); + } + + private static void Clone() + { + var db = GetInstance(); + var qy = db.Queryable().Where(it => 1 == 1); + + var list1 = qy.Clone().Where(it => it.Id == 1).ToList(); + var list2 = qy.Clone().Where(it => it.Id == 2).ToList(); + + + + var qy2 = db.Queryable((st,sc)=>new object[]{ + JoinType.Left,st.SchoolId==sc.Id + }).Where((st,sc)=>st.Id == 1); + + var join0 = qy2.Clone().Where((st, sc) => sc.Id == 222).Select(st=>st.Id).ToList(); + var join1 = qy2.Clone().Where((st,sc) => st.Id== 1111).ToList(); + var join2 = qy2.Clone().Where((st,sc)=>sc.Id==222).ToList(); + } + + private static void JoinExp() + { + var db = GetInstance(); + + var exp= Expressionable.Create() + .OrIF(1==1,it => it.Id == 11) + .And(it=>it.Id==1) + .AndIF(2==2,it => it.Id == 1) + .Or(it =>it.Name == "a1").ToExpression(); + var list=db.Queryable().Where(exp).ToList(); + } + + private static void ConditionalModel() + { + var db = GetInstance(); + List conModels = new List(); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 + conModels.Add(new ConditionalModel() { FieldName = "Student.id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Like, FieldValue = "1" });// id like '%1%' + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNullOrEmpty }); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.In,FieldValue="1,2,3" }); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NotIn, FieldValue = "1,2,3" }); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NoEqual, FieldValue = "1,2,3" }); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNot,FieldValue=null});// id is not null + + conModels.Add(new ConditionalCollections() { ConditionalList=new List>()// (id=1 or id=2 and id=1) + { + new KeyValuePair( WhereType.And ,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" }), + new KeyValuePair (WhereType.Or,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" }), + new KeyValuePair ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" }) + } + }); + var student = db.Queryable().Where(conModels).ToList(); + } + + private static void SelectMerge() + { + var db = GetInstance(); + //page join + var pageJoin = db.Queryable((st, sc) => new object[] { + JoinType.Left,st.SchoolId==sc.Id + }) + .Where(st => st.Id==1) + .Where(st => st.Id==2) + .Select((st, sc) => new { id = st.Id, name = sc.Name }) + .MergeTable().Where(XXX => XXX.id == 1).OrderBy("name asc").ToList();// Prefix, is, not, necessary, and take the columns in select + + } + private static void Where() + { + var db = GetInstance(); + //Parameterized processing + string value = "'jack';drop table Student"; + var list = db.Queryable().Where("name=@name", new { name = value }).ToList(); + //Nothing happened + } + + private static void OrderBy() + { + var db = GetInstance(); + //propertyName is valid + string propertyName = "Id"; + string dbColumnName = db.EntityMaintenance.GetDbColumnName(propertyName); + var list = db.Queryable().OrderBy(dbColumnName).ToList(); + + //propertyName is invalid + try + { + propertyName = "Id'"; + dbColumnName = db.EntityMaintenance.GetDbColumnName(propertyName); + var list2 = db.Queryable().OrderBy(dbColumnName).ToList(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/9_Aop.cs b/Src/Asp.Net/PgSqlTest/Demos/9_Aop.cs new file mode 100644 index 000000000..bb611497c --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/9_Aop.cs @@ -0,0 +1,87 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class Aop + { + + public static void Init() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.PostgreSQL, IsAutoCloseConnection = true }); + + + db.Aop.OnLogExecuted = (sql, pars) => + { + Console.Write("time:" + db.Ado.SqlExecutionTime.ToString()); + }; + db.Aop.OnLogExecuting = (sql, pars) => + { + + }; + db.Aop.OnError = (exp) => + { + + }; + db.Aop.OnExecutingChangeSql = (sql, pars) => + { + return new KeyValuePair(sql, pars); + }; + + db.Queryable().ToList(); + + try + { + db.Queryable().AS(" ' ").ToList(); + } + catch (Exception) + { + + + } + + + ////diff log demo + + //db.Aop.OnDiffLogEvent = it => + //{ + // var editBeforeData = it.BeforeData; + // var editAfterData = it.AfterData; + // var sql = it.Sql; + // var parameter = it.Parameters; + // var data = it.BusinessData; + //}; + + + //var id = db.Insertable(new Student() { Name = "beforeName" }) + //.EnableDiffLogEvent(new { title="add student"}) + //.ExecuteReturnIdentity(); + + + //db.Updateable(new Student() + //{ + // Id = id, + // CreateTime = DateTime.Now, + // Name = "afterName", + // SchoolId = 2 + //}) + //.EnableDiffLogEvent(new { title = "update Student", Modular = 1, Operator = "admin" }) + //.ExecuteCommand(); + + + //db.Deleteable(id) + //.EnableDiffLogEvent(new { title = "delete student" }) + //.ExecuteCommand(); + + + ////primary key guid + // db.Insertable(new DataTestInfo2() { Bool1=true, Bool2=false, PK=Guid.NewGuid(), Text1="a" }) + //.EnableDiffLogEvent(new { title = "add DataTestInfo2" }) + //.ExecuteReturnIdentity(); + } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/PgSqlTest/Demos/A_MasterSlave.cs b/Src/Asp.Net/PgSqlTest/Demos/A_MasterSlave.cs new file mode 100644 index 000000000..a571f1fa2 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/A_MasterSlave.cs @@ -0,0 +1,44 @@ +using OrmTest.Demo; +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class MasterSlave : DemoBase + { + + public static void Init() + { + + for (int i = 0; i < 10; i++) + { + var db = GetMasterSlaveInstance(); + var list = db.Insertable(new Student() { Name="aa" }).ExecuteCommand(); // ConnectionString2 or ConnectionString3 + } + //db.Insertable(new Student() { Name = "masterTest" }).ExecuteCommand();// Config.ConnectionString + } + + public static SqlSugarClient GetMasterSlaveInstance() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.PostgreSQL, + IsAutoCloseConnection = true, + SlaveConnectionConfigs = new List() { + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } , + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } + } + }); + db.Aop.OnLogExecuting = (sql, pars) => + { + Console.WriteLine(db.Ado.Connection.ConnectionString); + }; + return db; + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/B_SharedConnection.cs b/Src/Asp.Net/PgSqlTest/Demos/B_SharedConnection.cs new file mode 100644 index 000000000..1cbdf7a72 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/B_SharedConnection.cs @@ -0,0 +1,87 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class SharedConnection : DemoBase + { + public static void Init() + { + StudentDal studentDal = new StudentDal(); + SchoolDal schoolDal = new SchoolDal(); + + try + { + studentDal.BeginTran(); + + Console.WriteLine("school Count:"+ schoolDal.GetSchoolCount());//0 + + studentDal.AddStudent(new Student() { Name = "StudentTest" }); + schoolDal.AddSchool(new School() { Name = "SchoolTest" });//1 + + Console.WriteLine("school Count:" + schoolDal.GetSchoolCount()); + + throw new Exception("error"); + } + catch (Exception ex) + { + studentDal.RollbackTran(); + Console.WriteLine("school Count:" + schoolDal.GetSchoolCount());//0 + } + } + + + } + public class StudentDal : BaseDao + { + public void AddStudent(Student sudent) + { + db.Insertable(sudent).ExecuteCommand(); + } + } + public class SchoolDal : BaseDao + { + public void AddSchool(School school) + { + db.Insertable(school).ExecuteCommand(); + } + public int GetSchoolCount() + { + return db.Queryable().Count(); + } + } + + public class BaseDao + { + + public SqlSugar.SqlSugarClient db { get { return GetInstance(); } } + public void BeginTran() + { + db.Ado.BeginTran(); + } + public void CommitTran() + { + db.Ado.CommitTran(); + } + public void RollbackTran() + { + db.Ado.RollbackTran(); + } + public SqlSugarClient GetInstance() + { + SqlSugarClient db = new SqlSugarClient( + new ConnectionConfig() { + ConnectionString = Config.ConnectionString, + DbType = DbType.PostgreSQL, + IsAutoCloseConnection = false, + IsShardSameThread= true /*Shard Same Thread*/ + }); + + return db; + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/CS_TeacherStudent.cs b/Src/Asp.Net/PgSqlTest/Demos/CS_TeacherStudent.cs new file mode 100644 index 000000000..272ae4df2 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/CS_TeacherStudent.cs @@ -0,0 +1,88 @@ +using System; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class CS_TeacherStudent + { + + /// + /// Desc:- + /// Default:(newid()) + /// Nullable:False + /// + public Guid tabId {get;set;} + + /// + /// Desc:教师Id + /// Default:- + /// Nullable:False + /// + public string teacherId {get;set;} + + /// + /// Desc:教师课程Id(对应TeacherCourse.tabId) + /// Default:- + /// Nullable:False + /// + public string teacherCourseId {get;set;} + + /// + /// Desc:教学头内的序号 + /// Default:- + /// Nullable:True + /// + public int? ordInTC {get;set;} + + /// + /// Desc:学号 + /// Default:- + /// Nullable:False + /// + public string stuId {get;set;} + + /// + /// Desc:学生姓名 + /// Default:- + /// Nullable:True + /// + public string stuName {get;set;} + + /// + /// Desc:性别 + /// Default:- + /// Nullable:True + /// + public string stuSex {get;set;} + + /// + /// Desc:所属院系Id + /// Default:- + /// Nullable:True + /// + public string deptId {get;set;} + + /// + /// Desc:所属班级Id + /// Default:- + /// Nullable:True + /// + public string classId {get;set;} + + /// + /// Desc:不能对应班级代码的班级名称时源班级名称 + /// Default:- + /// Nullable:True + /// + public string sclassName {get;set;} + + /// + /// Desc:- + /// Default:((1)) + /// Nullable:True + /// + public int? validFlag {get;set;} + + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/C_ExtSqlFun.cs b/Src/Asp.Net/PgSqlTest/Demos/C_ExtSqlFun.cs new file mode 100644 index 000000000..ee9fbb943 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/C_ExtSqlFun.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SqlSugar; +using OrmTest.Models; + +namespace OrmTest.Demo +{ + public class ExtSqlFun : DemoBase + { + public static SqlSugarClient GetDb() + { + //Create ext method + var expMethods = new List(); + expMethods.Add(new SqlFuncExternal() + { + UniqueMethodName = "MyToString", + MethodValue = (expInfo, dbType, expContext) => + { + return string.Format("CAST({0} AS VARCHAR)", expInfo.Args[0].MemberName); + } + }); + + var config = new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.PostgreSQL, + IsAutoCloseConnection = true, + ConfigureExternalServices = new ConfigureExternalServices() + { + SqlFuncServices = expMethods//set ext method + } + }; + + SqlSugarClient db = new SqlSugarClient(config); + return db; + } + + public static string MyToString(T str) + { + throw new NotSupportedException("Can only be used in expressions"); + } + + public static void Init() + { + var db = GetDb(); + var list = db.Queryable().Where(it => MyToString(it.Id) == "1302583").ToList(); + var sql = db.Queryable().Where(it => MyToString(it.Id) == "1302583").ToSql(); + Console.WriteLine(sql); + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/D_QueryableView.cs b/Src/Asp.Net/PgSqlTest/Demos/D_QueryableView.cs new file mode 100644 index 000000000..3aaabe9c7 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/D_QueryableView.cs @@ -0,0 +1,33 @@ +using OrmTest.Models; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class QueryableView : DemoBase + { + public static void Init() + { + var db = GetInstance(); + var q1 = db.Queryable((st,sc)=>new object[] { + JoinType.Left,st.SchoolId==sc.Id + }).Select((st, sc) => new ViewModelStudent4() { Id=st.Id, Name=st.Name,SchoolName=sc.Name }); + + var q2 = db.Queryable(); + + + var innerJoinList = db.Queryable(q1, q2, (j1, j2) => j1.Id == j2.Id).Select((j1, j2) => j1).ToList();//inner join + + var leftJoinList = db.Queryable(q1, q2,JoinType.Left, (j1, j2) => j1.Id == j2.Id).Select((j1, j2) => j1).ToList();//left join + } + } + + public class ViewModelStudent4 { + public int Id { get; set; } + public string SchoolName { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/E_Attribute.cs b/Src/Asp.Net/PgSqlTest/Demos/E_Attribute.cs new file mode 100644 index 000000000..66c6cc57a --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/E_Attribute.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SqlSugar; +namespace OrmTest.Demo +{ + public class AttributeDemo : DemoBase + { + public static void Init() + { + var db = GetInstance(); + AttributeTest a = new AttributeTest() + { + Name = "attr" + }; + db.Insertable(a).AS("student").ExecuteCommand(); + var list = db.Queryable().AS("student").ToList(); + var list2 = db.Queryable().AS("student").Select(it => new AttributeTest() { Aid = it.Aid + 1,CreateTime=DateTime.Now,Name=it.Name }).ToList(); + var s = new AttributeTest2() { Aid = 1,AName="a", CreateTime=DateTime.Now }; + var count = db.Updateable(s).UpdateColumns(it=>new { it.CreateTime,it.AName }).Where(it=>it.Aid==100).ExecuteCommand(); + } + + public class AttributeTest + { + [SugarColumn(ColumnName = "Id")] + public int Aid { get; set; } + public string Name { get; set; } + [SugarColumn(IsOnlyIgnoreInsert = true)] + public DateTime CreateTime { get; set; } + } + [SugarTable("student")] + public class AttributeTest2 + { + [SugarColumn(ColumnName = "Id")] + public int Aid { get; set; } + [SugarColumn(ColumnName = "Name")] + public string AName { get; set; } + [SugarColumn(IsOnlyIgnoreInsert = true)] + public DateTime CreateTime { get; set; } + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/F_VersionValidation.cs b/Src/Asp.Net/PgSqlTest/Demos/F_VersionValidation.cs new file mode 100644 index 000000000..ac6789891 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/F_VersionValidation.cs @@ -0,0 +1,119 @@ +using OrmTest.Demo; +using OrmTest.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class VersionValidation : DemoBase + { + public static void Init() + { + TimestampDemo(); + DateTimeDemo(); + } + + private static void TimestampDemo() + { + var db = GetInstance(); + try + { + + var data = new StudentVersion() + { + Id = db.Queryable().Select(it => it.Id).First(), + CreateTime = DateTime.Now, + Name = "", + }; + db.Updateable(data).IgnoreColumns(it => new { it.Timestamp }).ExecuteCommand(); + + var time = db.Queryable().Where(it => it.Id == data.Id).Select(it => it.Timestamp).Single(); + + data.Timestamp = time; + + //is ok + db.Updateable(data).IsEnableUpdateVersionValidation().IgnoreColumns(it => new { it.Timestamp }).ExecuteCommand(); + //updated Timestamp change + + //is error + db.Updateable(data).IsEnableUpdateVersionValidation().IgnoreColumns(it => new { it.Timestamp }).ExecuteCommand(); + + //IsEnableUpdateVersionValidation Types of support int or long or byte[](Timestamp) or Datetime + + } + catch (Exception ex) + { + if (ex is SqlSugar.VersionExceptions) + { + Console.Write(ex.Message); + } + else + { + + } + } + } + private static void DateTimeDemo() + { + var db = GetInstance(); + try + { + + var data = new StudentVersion2() + { + Id = db.Queryable().Select(it => it.Id).First(), + CreateTime = DateTime.Now, + Name = "", + }; + db.Updateable(data).ExecuteCommand(); + + var time = db.Queryable().Where(it => it.Id == data.Id).Select(it => it.CreateTime).Single(); + + data.CreateTime = time; + + //is ok + db.Updateable(data).IsEnableUpdateVersionValidation().ExecuteCommand(); + + + data.CreateTime = time.AddMilliseconds(-1); + //is error + db.Updateable(data).IsEnableUpdateVersionValidation().ExecuteCommand(); + + //IsEnableUpdateVersionValidation Types of support int or long or byte[](Timestamp) or Datetime + + } + catch (Exception ex) + { + if (ex is SqlSugar.VersionExceptions) + { + Console.Write(ex.Message); + } + else + { + + } + } + } + + [SqlSugar.SugarTable("Student")] + public class StudentVersion + { + public int Id { get; set; } + public string Name { get; set; } + public DateTime CreateTime { get; set; } + [SqlSugar.SugarColumn(IsEnableUpdateVersionValidation = true,IsOnlyIgnoreInsert=true)] + public byte[] Timestamp { get; set; } + } + + [SqlSugar.SugarTable("Student")] + public class StudentVersion2 + { + public int Id { get; set; } + public string Name { get; set; } + [SqlSugar.SugarColumn(IsEnableUpdateVersionValidation = true, IsOnlyIgnoreInsert = true)] + public DateTime CreateTime { get; set; } + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/G_Mapper.cs b/Src/Asp.Net/PgSqlTest/Demos/G_Mapper.cs new file mode 100644 index 000000000..9915944e7 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/G_Mapper.cs @@ -0,0 +1,64 @@ +using OrmTest.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class Mapper : DemoBase + { + public static void Init() + { + var db = GetInstance(); + + //auto fill ViewModelStudent3 + var s11 = db.Queryable((st, sc) => st.SchoolId == sc.Id) + .Select().ToList(); + + + var s12 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Select() + + .Mapper((it, cache) => + { + + var allSchools = cache.GetListByPrimaryKeys(vmodel => vmodel.SchoolId); + //sql select shool where id (in(ViewModelStudent3[0].SchoolId , ViewModelStudent3[1].SchoolId...) + + //Equal to allSchools + //var allSchools2= cache.Get(list => + // { + // var ids=list.Select(i => it.SchoolId).ToList(); + // return db.Queryable().In(ids).ToList(); + //});Complex writing metho + + + /*one to one*/ + //Good performance + it.School = allSchools.FirstOrDefault(i => i.Id == it.SchoolId); + + //Poor performance. + //it.School = db.Queryable().InSingle(it.SchoolId); + + + /*one to many*/ + it.Schools = allSchools.Where(i => i.Id == it.SchoolId).ToList(); + + + /*C# syntax conversion*/ + it.Name = it.Name == null ? "null" : it.Name; + + }).ToList(); + + + var s13 = db.Queryable((st, sc) => st.SchoolId == sc.Id).Select() + + .Mapper((it, cache) => + { + it.Schools = db.Queryable().Where(i => i.Id == it.SchoolId).ToList(); + }).ToList(); + + + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/H_ExtEntity.cs b/Src/Asp.Net/PgSqlTest/Demos/H_ExtEntity.cs new file mode 100644 index 000000000..ef7935802 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/H_ExtEntity.cs @@ -0,0 +1,58 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + /// + /// mapping ef attribute + /// + public class ExtEntity: DemoBase + { + public static void Init() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { + ConnectionString = Config.ConnectionString, + DbType = DbType.PostgreSQL, + IsAutoCloseConnection = true, + ConfigureExternalServices=new ConfigureExternalServices() { + EntityService = (property, column) => { + if (property.Name == "xxx") {// by name ignore column + column.IsIgnore = true; + } + var attributes = property.GetCustomAttributes(true);//get all attributes + + if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey + { + column.IsPrimarykey = true; + } + }, + EntityNameService = (type,entity) => { + var attributes = type.GetCustomAttributes(true); + if (attributes.Any(it => it is TableAttribute)) + { + entity.DbTableName = (attributes.First(it => it is TableAttribute)as TableAttribute).Name; + } + } + } + }); + + var sql=db.Queryable().ToList(); + var sql2 = db.Insertable(new StudentTest()).ExecuteCommand(); + } + + } + + [Table("student")]//default + public class StudentTest { + + [Key] + public string Id { get; set; } + public string xxx { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/H_Queue.cs b/Src/Asp.Net/PgSqlTest/Demos/H_Queue.cs new file mode 100644 index 000000000..b9957cc5c --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/H_Queue.cs @@ -0,0 +1,65 @@ +using OrmTest.Demo; +using OrmTest.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class Queue : DemoBase + { + public static void Init() + { + var db = GetInstance(); + db.Insertable(new Student() { Name = "a" }).AddQueue(); + db.Insertable(new Student() { Name = "b" }).AddQueue(); + db.SaveQueues(); + + db.Insertable(new Student() { Name = "a" }).AddQueue(); + db.Insertable(new Student() { Name = "b" }).AddQueue(); + db.Insertable(new Student() { Name = "c" }).AddQueue(); + db.Insertable(new Student() { Name = "d" }).AddQueue(); + var ar = db.SaveQueuesAsync(); + ar.Wait(); + + + db.Queryable().AddQueue(); + db.Queryable().AddQueue(); + var result = db.SaveQueues(); + + db.Queryable().AddQueue(); + db.Queryable().AddQueue(); + db.AddQueue("select @id", new { id = 1 }); + var result2 = db.SaveQueues(); + + + + db.AddQueue("select 1"); + db.AddQueue("select 2"); + db.AddQueue("select 3"); + db.AddQueue("select 4"); + db.AddQueue("select 5"); + db.AddQueue("select 6"); + db.AddQueue("select 7"); + + var result3 = db.SaveQueues(); + + + db.AddQueue("select 1"); + var result4 = db.SaveQueues(); + + + db.AddQueue("select 1"); + db.AddQueue("select 2"); + var result5 = db.SaveQueues(); + + + db.AddQueue("select 1"); + db.AddQueue("select 2"); + db.AddQueue("select 3"); + var result6 = db.SaveQueuesAsync(); + result6.Wait(); + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Demos/PerformanceTest.cs b/Src/Asp.Net/PgSqlTest/Demos/PerformanceTest.cs new file mode 100644 index 000000000..3ac2b9286 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/PerformanceTest.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +namespace SyntacticSugar +{ + + public class PerformanceTest + { + private DateTime _beginTime; + private DateTime _endTime; + private ParamsModel _params; + private List _CharSource = new List(); + /// + ///设置执行次数(默认:1) + /// + public void SetCount(int count) + { + _params.RunCount = count; + } + /// + /// 设置线程模式(默认:false) + /// + /// true为多线程 + public void SetIsMultithread(bool isMul) + { + _params.IsMultithread = isMul; + } + + /// + /// 构造函数 + /// + public PerformanceTest() + { + _params = new ParamsModel() + { + RunCount = 1 + }; + } + + /// + /// 执行函数 + /// + /// + public void Execute(Action action, Action rollBack, string name = null) + { + List arr = new List(); + _beginTime = DateTime.Now; + for (int i = 0; i < _params.RunCount; i++) + { + if (_params.IsMultithread) + { + var thread = new Thread(new System.Threading.ThreadStart(() => + { + action(i); + })); + thread.Start(); + arr.Add(thread); + } + else + { + action(i); + } + } + if (_params.IsMultithread) + { + foreach (Thread t in arr) + { + while (t.IsAlive) + { + Thread.Sleep(10); + } + } + + } + + _CharSource.Add(new PerformanceTestChartModel() { Name = name, Time = GetTime(), CPU = GetCurrentProcessSize() }); + rollBack(string.Format("总共执行时间:{0}秒", GetTime())); + } + + private double GetTime() + { + _endTime = DateTime.Now; + double totalTime = ((_endTime - _beginTime).TotalMilliseconds / 1000.0); + return totalTime; + } + + public List GetChartSource() + { + return _CharSource; + } + private Double GetCurrentProcessSize() + { + Process processes = Process.GetCurrentProcess(); + var processesSize = (Double)(processes.WorkingSet64); + return processesSize / (1024 * 1024); + } + + private class ParamsModel + { + public int RunCount { get; set; } + public bool IsMultithread { get; set; } + } + public class PerformanceTestChartModel + { + public string Name { get; set; } + public double Time { get; set; } + public double CPU { get; set; } + } + } + + +} \ No newline at end of file diff --git a/Src/Asp.Net/PgSqlTest/Demos/Z_DemoBase.cs b/Src/Asp.Net/PgSqlTest/Demos/Z_DemoBase.cs new file mode 100644 index 000000000..fc59f2852 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Demos/Z_DemoBase.cs @@ -0,0 +1,22 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Demo +{ + public class DemoBase + { + public static SqlSugarClient GetInstance() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.PostgreSQL, IsAutoCloseConnection = true }); + db.Aop.OnLogExecuting = (sql, pars) => + { + Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); + Console.WriteLine(); + }; + return db; + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Models/DataTestInfo.cs b/Src/Asp.Net/PgSqlTest/Models/DataTestInfo.cs new file mode 100644 index 000000000..935aefaff --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Models/DataTestInfo.cs @@ -0,0 +1,135 @@ +using System; +using System.Linq; +using System.Text; + +namespace OrmTest.Models +{ + /// + /// + /// + public class DataTestInfo + { + public DataTestInfo(){ + + } + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public int Int1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public int? Int2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public string String {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public decimal Decimal1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public decimal? Decimal2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public DateTime Datetime1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public DateTime? Datetime2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public byte[] Image1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public byte[] Image2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public Guid Guid1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public Guid? Guid2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public decimal Money1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public decimal? Money2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public byte[] Varbinary1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public byte[] Varbinary2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public double Float1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public double? Float2 {get;set;} + + } +} diff --git a/Src/Asp.Net/PgSqlTest/Models/DataTestInfo2.cs b/Src/Asp.Net/PgSqlTest/Models/DataTestInfo2.cs new file mode 100644 index 000000000..8f425a4c1 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Models/DataTestInfo2.cs @@ -0,0 +1,44 @@ +using System; +using System.Linq; +using System.Text; + +namespace OrmTest.Models +{ + /// + /// + /// + public class DataTestInfo2 + { + public DataTestInfo2(){ + + } + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public Guid PK {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:False + /// + public bool Bool1 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public bool? Bool2 {get;set;} + + /// + /// Desc: + /// Default: + /// Nullable:True + /// + public string Text1 {get;set;} + + } +} diff --git a/Src/Asp.Net/PgSqlTest/Models/Enum.cs b/Src/Asp.Net/PgSqlTest/Models/Enum.cs new file mode 100644 index 000000000..09102a410 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Models/Enum.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest.Models +{ + public enum SchoolEnum + { + HarvardUniversity = 0, + UniversityOfOxford = 1 + } + public class StudentEnum + { + public int Id { get; set; } + public SchoolEnum SchoolId { get; set; } + public string Name { get; set; } + public DateTime? CreateTime { get; set; } + [SqlSugar.SugarColumn(IsIgnore =true)] + public int TestId { get; set; } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Models/School.cs b/Src/Asp.Net/PgSqlTest/Models/School.cs new file mode 100644 index 000000000..c3f8175b6 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Models/School.cs @@ -0,0 +1,18 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Models +{ + public class School + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + [SugarColumn(Length = 50,IsNullable =true)] + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Models/Student.cs b/Src/Asp.Net/PgSqlTest/Models/Student.cs new file mode 100644 index 000000000..55f024c62 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Models/Student.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SqlSugar; +using System.Linq.Expressions; + +namespace OrmTest.Models +{ + [SugarTable("STudent")] + public class Student + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "ID")] + public int Id { get; set; } + [SugarColumn(IsNullable =true)] + public int? SchoolId { get; set; } + [SugarColumn(Length =50,IsNullable =true)] + public string Name { get; set; } + [SugarColumn(IsNullable = true)] + public DateTime? CreateTime { get; set; } + [SugarColumn(IsIgnore=true)] + public int TestId { get; set; } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Models/ViewModelStudent.cs b/Src/Asp.Net/PgSqlTest/Models/ViewModelStudent.cs new file mode 100644 index 000000000..3ef6abee4 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Models/ViewModelStudent.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest.Models +{ + public class ViewModelStudent:Student + { + + } + public class ViewModelStudent2 + { + public string Name { get; set; } + public Student Student { get; set; } + } + public class ViewModelStudent3: Student + { + public string SchoolName { get; set; } + public string School_Name { get; set; } + public string ScId { get; set; } + public School School { get; set; } + public List Schools { get; set; } + } +} diff --git a/Src/Asp.Net/PgSqlTest/PgSqlTest.csproj b/Src/Asp.Net/PgSqlTest/PgSqlTest.csproj new file mode 100644 index 000000000..7b2682c91 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/PgSqlTest.csproj @@ -0,0 +1,85 @@ + + + + + Debug + AnyCPU + {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99} + Library + Properties + PgSqlTest + PgSqlTest + v4.5 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {489bb790-226c-4fad-8d1e-51d72a7ff8e5} + SqlSugar + + + + \ No newline at end of file diff --git a/Src/Asp.Net/PgSqlTest/Program.cs b/Src/Asp.Net/PgSqlTest/Program.cs new file mode 100644 index 000000000..4301f6fcc --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Program.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using System.Linq.Expressions; +using SqlSugar; +using OrmTest.Models; +using System.Data.SqlClient; + + +namespace OrmTest +{ + class Program + { + static void Main(string[] args) + { + Demo.DbFirst.Init(); + Demo.CodeFirst.Init(); + Demo.Aop.Init(); + Demo.Query.Init(); + Demo.Insert.Init(); + Demo.Delete.Init(); + Demo.Update.Init(); + Demo.MasterSlave.Init(); + Demo.SharedConnection.Init(); + Demo.ExtSqlFun.Init(); + //Demo.QueryableView.Init(); + Demo.AttributeDemo.Init(); + Demo.Mapper.Init(); + Demo.ExtEntity.Init(); + Demo.Queue.Init(); + + } + } +} diff --git a/Src/Asp.Net/PgSqlTest/Properties/AssemblyInfo.cs b/Src/Asp.Net/PgSqlTest/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..b2c00fdf0 --- /dev/null +++ b/Src/Asp.Net/PgSqlTest/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("PgSqlTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PgSqlTest")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("86a55d46-b5f5-44b4-8b60-2aed1e2edd99")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Src/Asp.Net/SqlSugar.sln b/Src/Asp.Net/SqlSugar.sln index aafa68147..bb5c721eb 100644 --- a/Src/Asp.Net/SqlSugar.sln +++ b/Src/Asp.Net/SqlSugar.sln @@ -25,6 +25,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NugetTest", "NugetTest\Nuge EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlSugar.DbFirstExtensions", "SqlSugar.DbFirstExtensions\SqlSugar.DbFirstExtensions.csproj", "{629CDF51-682F-4B22-843A-BA76C232ACCD}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PgSqlTest", "PgSqlTest\PgSqlTest.csproj", "{86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -71,6 +73,10 @@ Global {629CDF51-682F-4B22-843A-BA76C232ACCD}.Debug|Any CPU.Build.0 = Debug|Any CPU {629CDF51-682F-4B22-843A-BA76C232ACCD}.Release|Any CPU.ActiveCfg = Release|Any CPU {629CDF51-682F-4B22-843A-BA76C232ACCD}.Release|Any CPU.Build.0 = Release|Any CPU + {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}.Debug|Any CPU.Build.0 = Debug|Any CPU + {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}.Release|Any CPU.ActiveCfg = Release|Any CPU + {86A55D46-B5F5-44B4-8B60-2AED1E2EDD99}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs b/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs index ac22fc1bd..f8f6ab2c1 100644 --- a/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs +++ b/Src/Asp.Net/SqlSugar/Infrastructure/DependencyManagement.cs @@ -12,6 +12,7 @@ namespace SqlSugar private static bool IsTryMySqlData = false; private static bool IsTrySqlite = false; private static bool IsTryOracle = false; + private static bool IsTryPgSql = false; public static void TryJsonNet() { if (!IsTryJsonNet) @@ -50,12 +51,24 @@ namespace SqlSugar } } - internal static void TryPostgreSQL() + public static void TryPostgreSQL() { - var message = ErrorMessage.GetThrowMessage( - "SqlSugar PostGreSQL only support.NET CORE", - "SqlSugar使用 PostGreSQL只支持.NET CORE"); - throw new Exception(message); + if (!IsTryPgSql) + { + try + { + PostgreSQLProvider db = new PostgreSQLProvider(); + var conn = db.GetAdapter(); + IsTryPgSql = true; + } + catch + { + var message = ErrorMessage.GetThrowMessage( + "You need to refer to Npgsql.dll", + "需要引用Npgsql.dll,请在Nuget安装最新稳定版本,如果有版本兼容问题请先删除原有引用"); + throw new Exception(message); + } + } } internal static void TryOracle()