From 56571c99d54fcb50928faa0353bb7f46b2fda8d6 Mon Sep 17 00:00:00 2001 From: sunkaixuan <610262374@qq.com> Date: Sun, 20 Feb 2022 14:13:19 +0800 Subject: [PATCH] Add AccessTest --- Src/Asp.Net/AccessTest/AccessTest.csproj | 100 +++ Src/Asp.Net/AccessTest/App.config | 3 + Src/Asp.Net/AccessTest/Config.cs | 31 + .../AccessTest/Demo/Demo0_SqlSugarClient.cs | 450 ++++++++++++++ .../AccessTest/Demo/Demo1_Queryable.cs | 571 ++++++++++++++++++ .../AccessTest/Demo/Demo2_Updateable.cs | 118 ++++ .../AccessTest/Demo/Demo3_Insertable.cs | 331 ++++++++++ .../AccessTest/Demo/Demo4_Deleteable.cs | 59 ++ .../AccessTest/Demo/Demo5_SqlQueryable.cs | 36 ++ Src/Asp.Net/AccessTest/Demo/Demo6_Queue.cs | 53 ++ Src/Asp.Net/AccessTest/Demo/Demo7_Ado.cs | 78 +++ Src/Asp.Net/AccessTest/Demo/Demo8_Saveable.cs | 69 +++ .../AccessTest/Demo/Demo9_EntityMain.cs | 46 ++ Src/Asp.Net/AccessTest/Demo/DemoA_DbMain.cs | 42 ++ Src/Asp.Net/AccessTest/Demo/DemoB_Aop.cs | 77 +++ Src/Asp.Net/AccessTest/Demo/DemoD_DbFirst.cs | 75 +++ .../AccessTest/Demo/DemoE_CodeFirst.cs | 40 ++ .../AccessTest/Demo/DemoF_Utilities.cs | 46 ++ .../AccessTest/Demo/DemoG_SimpleClient.cs | 64 ++ Src/Asp.Net/AccessTest/Demo/DemoH_Tenant.cs | 82 +++ Src/Asp.Net/AccessTest/Demo/DemoJ_Report.cs | 142 +++++ .../AccessTest/Demo/DemoL_Snowflake.cs | 49 ++ .../AccessTest/Demo/DemoM_UnitOfWork.cs | 72 +++ .../AccessTest/Demo/DemoN_SplitTable.cs | 100 +++ .../AccessTest/Demo/Democ_GobalFilter.cs | 108 ++++ .../AccessTest/Models/AttributeTable.cs | 20 + Src/Asp.Net/AccessTest/Models/Custom.cs | 14 + .../AccessTest/Models/DataDictionary.cs | 34 ++ Src/Asp.Net/AccessTest/Models/EntityMapper.cs | 15 + Src/Asp.Net/AccessTest/Models/Mapper.cs | 56 ++ Src/Asp.Net/AccessTest/Models/Order.cs | 24 + Src/Asp.Net/AccessTest/Models/OrderItem.cs | 20 + .../AccessTest/Models/SubInsertTest.cs | 108 ++++ Src/Asp.Net/AccessTest/Models/TestTree.cs | 17 + Src/Asp.Net/AccessTest/Models/Tree.cs | 20 + Src/Asp.Net/AccessTest/Models/ViewOrder.cs | 13 + Src/Asp.Net/AccessTest/Program.cs | 46 ++ .../AccessTest/Properties/AssemblyInfo.cs | 36 ++ Src/Asp.Net/SqlSugar.sln | 6 + 39 files changed, 3271 insertions(+) create mode 100644 Src/Asp.Net/AccessTest/AccessTest.csproj create mode 100644 Src/Asp.Net/AccessTest/App.config create mode 100644 Src/Asp.Net/AccessTest/Config.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo0_SqlSugarClient.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo1_Queryable.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo2_Updateable.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo3_Insertable.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo4_Deleteable.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo5_SqlQueryable.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo6_Queue.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo7_Ado.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo8_Saveable.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Demo9_EntityMain.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoA_DbMain.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoB_Aop.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoD_DbFirst.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoE_CodeFirst.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoF_Utilities.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoG_SimpleClient.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoH_Tenant.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoJ_Report.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoL_Snowflake.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoM_UnitOfWork.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/DemoN_SplitTable.cs create mode 100644 Src/Asp.Net/AccessTest/Demo/Democ_GobalFilter.cs create mode 100644 Src/Asp.Net/AccessTest/Models/AttributeTable.cs create mode 100644 Src/Asp.Net/AccessTest/Models/Custom.cs create mode 100644 Src/Asp.Net/AccessTest/Models/DataDictionary.cs create mode 100644 Src/Asp.Net/AccessTest/Models/EntityMapper.cs create mode 100644 Src/Asp.Net/AccessTest/Models/Mapper.cs create mode 100644 Src/Asp.Net/AccessTest/Models/Order.cs create mode 100644 Src/Asp.Net/AccessTest/Models/OrderItem.cs create mode 100644 Src/Asp.Net/AccessTest/Models/SubInsertTest.cs create mode 100644 Src/Asp.Net/AccessTest/Models/TestTree.cs create mode 100644 Src/Asp.Net/AccessTest/Models/Tree.cs create mode 100644 Src/Asp.Net/AccessTest/Models/ViewOrder.cs create mode 100644 Src/Asp.Net/AccessTest/Program.cs create mode 100644 Src/Asp.Net/AccessTest/Properties/AssemblyInfo.cs diff --git a/Src/Asp.Net/AccessTest/AccessTest.csproj b/Src/Asp.Net/AccessTest/AccessTest.csproj new file mode 100644 index 000000000..fbb94edc7 --- /dev/null +++ b/Src/Asp.Net/AccessTest/AccessTest.csproj @@ -0,0 +1,100 @@ + + + + + Debug + AnyCPU + {FA1B8C67-44C2-4937-96A2-7E01B9F5941E} + Exe + AccessTest + AccessTest + v4.6 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Designer + + + + + {0a27f276-d442-4e0a-b810-32d6074f0155} + SqlSugar.Access + + + {489bb790-226c-4fad-8d1e-51d72a7ff8e5} + SqlSugar + + + + \ No newline at end of file diff --git a/Src/Asp.Net/AccessTest/App.config b/Src/Asp.Net/AccessTest/App.config new file mode 100644 index 000000000..b45f31e87 --- /dev/null +++ b/Src/Asp.Net/AccessTest/App.config @@ -0,0 +1,3 @@ + + + diff --git a/Src/Asp.Net/AccessTest/Config.cs b/Src/Asp.Net/AccessTest/Config.cs new file mode 100644 index 000000000..2adf5d443 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Config.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + /// + /// Setting up the database name does not require you to create the database + /// 只需要设置IP和账户密码 ,自动建库 + /// + public class Config + { + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST"; + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString2 = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST2"; + /// + /// Account have permission to create database + /// 用有建库权限的数据库账号 + /// + public static string ConnectionString3 = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST3"; + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo0_SqlSugarClient.cs b/Src/Asp.Net/AccessTest/Demo/Demo0_SqlSugarClient.cs new file mode 100644 index 000000000..b1db9ed6a --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo0_SqlSugarClient.cs @@ -0,0 +1,450 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SqlSugar; +namespace OrmTest +{ + public class Demo0_SqlSugarClient + { + + public static void Init() + { + SqlSugarClient();//Create db + DbContext();//Optimizing SqlSugarClient usage + SingletonPattern();//Singleten Pattern + DistributedTransactionExample(); + MasterSlave();//Read-write separation + CustomAttribute(); + } + + private static void MasterSlave() + { + Console.WriteLine(""); + Console.WriteLine("#### MasterSlave Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString,//Master Connection + DbType = DbType.SqlServer, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + SlaveConnectionConfigs = new List() { + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } , + new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } + } + }); + db.Aop.OnLogExecuted = (s, p) => + { + Console.WriteLine(db.Ado.Connection.ConnectionString); + }; + Console.WriteLine("Master:"); + db.Insertable(new Order() { Name = "abc", CustomId = 1, CreateTime = DateTime.Now }).ExecuteCommand(); + Console.WriteLine("Slave:"); + db.Queryable().First(); + Console.WriteLine("#### MasterSlave End ####"); + } + + private static void SqlSugarClient() + { + //Create db + Console.WriteLine("#### SqlSugarClient Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + //If no exist create datebase + db.DbMaintenance.CreateDatabase(); + + //Use db query + var dt = db.Ado.GetDataTable("select 1"); + + //Create tables + db.CodeFirst.InitTables(typeof(OrderItem),typeof(Order)); + var id = db.Insertable(new Order() { Name = "order1", CustomId = 1, Price = 0, CreateTime = DateTime.Now }).ExecuteReturnIdentity(); + + //Insert data + db.Insertable(new OrderItem() { OrderId = id, Price = 0, CreateTime=DateTime.Now }).ExecuteCommand(); + Console.WriteLine("#### SqlSugarClient End ####"); + + } + + private static void DbContext() + { + Console.WriteLine(""); + Console.WriteLine("#### DbContext Start ####"); + var insertObj = new Order { Name = "jack", CreateTime = DateTime.Now }; + var InsertObjs = new Order[] { insertObj }; + + DbContext context = new DbContext(); + + context.Db.CodeFirst.InitTables();//Create Tables + ; + var orderDb = context.OrderDb; + + //Select + var data1 = orderDb.GetById(1); + var data2 = orderDb.GetList(); + var data3 = orderDb.GetList(it => it.Id == 1); + var data4 = orderDb.GetSingle(it => it.Id == 1); + var p = new PageModel() { PageIndex = 1, PageSize = 2 }; + var data5 = orderDb.GetPageList(it => it.Name == "xx", p); + Console.Write(p.TotalCount); + var data6 = orderDb.GetPageList(it => it.Name == "xx", p, it => it.Name, OrderByType.Asc); + Console.Write(p.TotalCount); + List conModels = new List(); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 + var data7 = orderDb.GetPageList(conModels, p, it => it.Name, OrderByType.Asc); + orderDb.AsQueryable().Where(x => x.Id == 1).ToList(); + + //Insert + orderDb.Insert(insertObj); + orderDb.InsertRange(InsertObjs); + var id = orderDb.InsertReturnIdentity(insertObj); + orderDb.AsInsertable(insertObj).ExecuteCommand(); + + + //Delete + orderDb.Delete(insertObj); + orderDb.DeleteById(11111); + orderDb.DeleteById(new int[] { 1111, 2222 }); + orderDb.Delete(it => it.Id == 1111); + orderDb.AsDeleteable().Where(it => it.Id == 1111).ExecuteCommand(); + + //Update + orderDb.Update(insertObj); + orderDb.UpdateRange(InsertObjs); + orderDb.Update(it => new Order() { Name = "a", }, it => it.Id == 1); + orderDb.AsUpdateable(insertObj).UpdateColumns(it => new { it.Name }).ExecuteCommand(); + + //Use Inherit DbContext + OrderDal dal = new OrderDal(); + var data = dal.GetById(1); + var list = dal.GetList(); + + Console.WriteLine("#### DbContext End ####"); + } + + private static void CustomAttribute() + { + Console.WriteLine(""); + Console.WriteLine("#### Custom Attribute Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.SqlServer, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute, + ConfigureExternalServices = new ConfigureExternalServices() + { + EntityService = (property, column) => + { + + 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; + } + } + } + }); + db.CodeFirst.InitTables();//Create Table + + db.Insertable(new AttributeTable() { Id = Guid.NewGuid().ToString(), Name = "Name" }).ExecuteCommand(); + var list = db.Queryable().ToList(); + + Console.WriteLine("#### Custom Attribute End ####"); + } + + + private static void SingletonPattern() + { + Console.WriteLine(""); + Console.WriteLine("#### Singleton Pattern Start ####"); + Console.WriteLine("Db_Id:" + singleDb.ContextID); + Console.WriteLine("Db_Id:" + singleDb.ContextID); + var task = new Task(() => + { + Console.WriteLine("Task DbId:" + singleDb.ContextID); + new Task(() => + { + Console.WriteLine("_Task_Task DbId:" + singleDb.ContextID); + Console.WriteLine("_Task_Task DbId:" + singleDb.ContextID); + + }).Start(); + Console.WriteLine("Task DbId:" + singleDb.ContextID); + }); + task.Start(); + task.Wait(); + System.Threading.Thread.Sleep(500); + Console.WriteLine(string.Join(",", singleDb.TempItems.Keys)); + + Console.WriteLine("#### Singleton Pattern end ####"); + } + + static SqlSugarScope singleDb = new SqlSugarScope( + new ConnectionConfig() + { + ConfigId = 1, + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents() + { + OnLogExecuting = (sql, p) => { Console.WriteLine(sql); } + } + }); + + + private static void DistributedTransactionExample() + { + Console.WriteLine(""); + Console.WriteLine("#### Distributed TransactionExample Start ####"); + SqlSugarClient db = new SqlSugarClient(new List() + { + new ConnectionConfig(){ ConfigId="1", DbType=DbType.SqlServer, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true }, + new ConnectionConfig(){ ConfigId="2", DbType=DbType.SqlServer, ConnectionString=Config.ConnectionString2 ,InitKeyType=InitKeyType.Attribute ,IsAutoCloseConnection=true} + }); + + //use db1 + db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order), typeof(OrderItem));// + db.Insertable(new Order() { Name = "order1", CreateTime = DateTime.Now }).ExecuteCommand(); + Console.WriteLine(db.CurrentConnectionConfig.DbType + ":" + db.Queryable().Count()); + + //use db2 + db.ChangeDatabase("2"); + db.DbMaintenance.CreateDatabase();//Create Database2 + db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order), typeof(OrderItem)); + db.Insertable(new Order() { Name = "order1", CreateTime = DateTime.Now }).ExecuteCommand(); + Console.WriteLine(db.CurrentConnectionConfig.DbType + ":" + db.Queryable().Count()); + + // Example 1 + Console.WriteLine("Example 1"); + try + { + db.BeginTran(); + + db.ChangeDatabase("1");//use db1 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + throw new Exception(); + db.CommitTran(); + } + catch + { + db.RollbackTran(); + Console.WriteLine("---Roll back"); + db.ChangeDatabase("1");//use db1 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + } + + + + // Example 2 + Console.WriteLine("Example 2"); + + var result = db.UseTran(() => + { + + db.ChangeDatabase("1");//use db1 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + db.Deleteable().ExecuteCommand(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + throw new Exception(""); + + }); + if (result.IsSuccess == false) + { + Console.WriteLine("---Roll back"); + db.ChangeDatabase("1");//use db1 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + } + + // Example 3 + Console.WriteLine("Example 3"); + Task> result2 = AsyncTranDemo(db); + result2.Wait(); + + // Example 4 + Console.WriteLine("Example 4"); + var mysqldb = db.GetConnection("1");//获取ConfigId为1的数据库对象 + var sqlServerdb = db.GetConnection("2");//获取默认对象 + Console.WriteLine(mysqldb.Queryable().Count()); + Console.WriteLine(sqlServerdb.Queryable().Count()); + try + { + db.BeginTran(); + + sqlServerdb.Deleteable().ExecuteCommand(); + mysqldb.Deleteable().ExecuteCommand(); + Console.WriteLine(mysqldb.Queryable().Count()); + Console.WriteLine(sqlServerdb.Queryable().Count()); + + throw new Exception(""); + db.CommitTran(); + } + catch (Exception) + { + db.RollbackTran();//数据回滚 + Console.WriteLine(mysqldb.Queryable().Count()); + Console.WriteLine(sqlServerdb.Queryable().Count()); + } + Console.WriteLine("#### Distributed TransactionExample End ####"); + } + + /// + ///Async tran demo + /// + /// + /// + private static async Task> AsyncTranDemo(SqlSugarClient db) + { + //need await all + var result2 =await db.UseTranAsync(async () => + { + //need await all + + db.ChangeDatabase("1");//use db1 + await db.Deleteable().ExecuteCommandAsync(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use db2 + await db.Deleteable().ExecuteCommandAsync(); + Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + throw new Exception(""); + + }); + Console.WriteLine("---Roll back"); + db.ChangeDatabase("1");//use sqlserver + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + + db.ChangeDatabase("2");//use mysql + Console.WriteLine(db.CurrentConnectionConfig.DbType); + Console.WriteLine(db.Queryable().Count()); + return result2; + } + } + + /// + /// DbContext Example 1 + /// + public class DbContext + { + + public SqlSugarClient Db; + public DbContext() + { + Db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.SqlServer, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute, + AopEvents = new AopEvents() + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + } + } + }); + } + public SimpleClient OrderDb => new SimpleClient(Db); + public SimpleClient OrderItemDb => new SimpleClient(Db); + } + + + public class OrderDal : DbContext + { + + } + /// + /// DbContext Example 2 + /// + /// + public class DbContext where T : class, new() + { + + public SqlSugarClient Db; + public DbContext() + { + Db = new SqlSugarClient(new ConnectionConfig() + { + ConnectionString = Config.ConnectionString, + DbType = DbType.SqlServer, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute, + AopEvents = new AopEvents() + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + } + } + }); + } + public SimpleClient CurrentDb => new SimpleClient(Db); + public virtual T GetById(int id) + { + return CurrentDb.GetById(id); + } + public virtual List GetList() + { + return CurrentDb.GetList(); + } + public virtual bool Delete(int id) + { + return CurrentDb.DeleteById(id); + } + } + +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo1_Queryable.cs b/Src/Asp.Net/AccessTest/Demo/Demo1_Queryable.cs new file mode 100644 index 000000000..a6f28aa91 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo1_Queryable.cs @@ -0,0 +1,571 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Data; +using System.Dynamic; +using System.Linq; +using System.Text; +namespace OrmTest +{ + public class Demo1_Queryable + { + + public static void Init() + { + EasyExamples(); + QueryConditions(); + JoinTable(); + Async(); + NoEntity(); + Mapper(); + SqlFuncTest(); + Subquery(); + ReturnType(); + ConfiQuery(); + } + + private static void ConfiQuery() + { + var db = GetInstance(); + List datas = new List(); + datas.Add(new DataDictionary() { Code="1", Name="男",Type="sex" }); + datas.Add(new DataDictionary() { Code = "2", Name = "女", Type = "sex" }); + datas.Add(new DataDictionary() { Code = "1", Name = "南通市", Type = "city" }); + datas.Add(new DataDictionary() { Code = "2", Name = "苏州市", Type = "city" }); + datas.Add(new DataDictionary() { Code = "1", Name = "江苏省", Type = "province" }); + datas.Add(new DataDictionary() { Code = "2", Name = "湖南省", Type = "province" }); + db.CodeFirst.InitTables(); + db.CodeFirst.InitTables(); + db.DbMaintenance.TruncateTable(); + db.Insertable(datas).ExecuteCommand(); + + if (!db.ConfigQuery.Any()) + { + var types= db.Queryable().Select(it => it.Type).Distinct().ToList(); + foreach (var type in types) + { + db.ConfigQuery.SetTable(it => it.Code, it => it.Name, type, it => it.Type == type); + } + + db.ConfigQuery.SetTable(it => it.Id, it => it.Name, "01", it => it.Id > 1); + db.ConfigQuery.SetTable(it => it.Id, it => it.Name, "02", it => it.Id > 2); + db.ConfigQuery.SetTable(it => it.Id, it => it.Name, null); + } + + + var res=db.Queryable().Select(it => new Person() + { + Id=it.Id.SelectAll(), + SexName=it.SexId.GetConfigValue("sex"), + ProviceName = it.SexId.GetConfigValue("province"), + CityName = it.SexId.GetConfigValue("city"), + }).ToList();//也支持支持写在Where或者Orderby + + var list = db.Queryable().Select(it => new OrderItem + { + ItemId = it.ItemId.SelectAll(), + OrderName = it.OrderId.GetConfigValue("01") + }).ToList(); + var list2 = db.Queryable().Select(it => new OrderItem + { + ItemId = it.ItemId.SelectAll(), + OrderName = it.OrderId.GetConfigValue("02") + }).ToList(); + var list3 = db.Queryable().Select(it => new OrderItem + { + ItemId = it.ItemId.SelectAll(), + OrderName = it.OrderId.GetConfigValue() + }).ToList(); + + var list4 = db.Queryable().Select(it => new OrderItem + { + ItemId = it.ItemId.SelectAll(), + OrderName = it.OrderId.GetConfigValue() + }) + .Where(it=>it.OrderId.GetConfigValue()== "order1") + .OrderBy(it=>it.OrderId.GetConfigValue()).ToList(); + + var list5 = db.Queryable((o, i) => o.Id == i.OrderId) + .OrderBy((o,i)=>i.OrderId.GetConfigValue(),OrderByType.Desc) + .Select((o,i)=>new ViewOrder() { + Id= o.Id.SelectAll(), + Name=i.OrderId.GetConfigValue() + }) + .ToList(); + } + + private static void EasyExamples() + { + Console.WriteLine(""); + Console.WriteLine("#### Examples Start ####"); + var db = GetInstance(); + var dbTime = db.GetDate(); + var getAll = db.Queryable().Where(it=> SqlFunc.EqualsNull(it.Name,null)).ToList(); + var getOrderBy = db.Queryable().OrderBy(it => it.Name,OrderByType.Desc).ToList(); + var getOrderBy2 = db.Queryable().OrderBy(it => it.Id).OrderBy(it => it.Name, OrderByType.Desc).ToList(); + var getOrderBy3 = db.Queryable().OrderBy(it =>new { it.Name,it.Id}).ToList(); + var getRandom = db.Queryable().OrderBy(it => SqlFunc.GetRandom()).First(); + 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 getByFuns2 = db.Queryable().GroupBy(it => it.Name).Select(it => SqlFunc.AggregateDistinctCount(it.Price)).ToList(); + var getDicionary = db.Queryable().ToDictionary(it => it.Id, it => it.Name); + var getDicionaryList = db.Queryable().ToDictionaryList(); + var getTest = db.Queryable().Where(it =>string.IsNullOrWhiteSpace( it.Name)).ToList(); + var test01 = db.Queryable().PartitionBy(it => it.Id).ToList(); + var q1 = db.Queryable().Take(1); + var q2 = db.Queryable().Take(2); + var test02 = db.Union(q1, q2).ToList(); + var test03 = db.Queryable().Take(1).ToList(); + var dp = DateTime.Now; + var test05 = db.Queryable().Where(it => it.CreateTime.Month== dp.Month).ToList(); + var test06 = db.Queryable() + .ToPivotTable(it => it.Id, it => it.Name, it => it.Sum(x => x.Price)); + + var test07 = db.Queryable() + .ToPivotList(it => it.Id, it => it.Name, it => it.Sum(x => x.Price)); + + var test08 = db.Queryable() + .ToPivotJson(it => it.Id, it => it.Name, it => it.Sum(x => x.Price)); + + var test09 = db.Queryable().PartitionBy(it=>it.Id).ToPageListAsync(1,2,0); + test09.Wait(); + + int c = 0; + var test10 = db.Queryable().ToPageList(1, 2, ref c); + var test11 = db.Queryable().GroupBy(it=>new { it.CreateTime.Year }).Select(it=>it.CreateTime.Year).ToList(); + var test12 = db.Queryable().GroupBy(it => it.CreateTime.Date ).Select(it => it.CreateTime.Date).ToList(); + var test13 = db.Queryable().GroupBy(it => new { it.CreateTime.Date ,it.CreateTime.Year,it.CreateTime.Minute }) + .Select(it => new { it.CreateTime.Date, it.CreateTime.Year, it.CreateTime.Minute }).ToList(); + var test14 = db.Queryable() + .GroupBy(it => it.CreateTime.Year ) + .GroupBy(it => it.CreateTime.Second) + .GroupBy(it => it.CreateTime.Date) + .Select(it => new { + it.CreateTime.Year, + it.CreateTime.Second, + it.CreateTime.Date + }).ToList(); + var test15 = db.Queryable((o, i) => new JoinQueryInfos( + JoinType.Left, o.Name == SqlFunc.ToString(SqlFunc.MergeString(",", i.Name, ",")) + )) + .Select().ToList(); + var test16 = db.Queryable().Select(it => SqlFunc.SqlServer_DateDiff("day", DateTime.Now.AddDays(-1), DateTime.Now)).ToList(); + var test17 = + db.Queryable() + .Select() + .MergeTable() + .Select(it => new ViewOrder() + { + Name = SqlFunc.Subqueryable().Select(s => s.Name) + }).ToList(); ; + var test18 = db.UnionAll( + db.Queryable() , + db.Queryable() + ) + .Select(it=>new ViewOrder(){ + Name=SqlFunc.Subqueryable().Select(s=>s.Name) + }).ToList(); + var test19 = db.Queryable().Select().ToList(); + var test20 = db.Queryable().LeftJoin((o, cs) =>o.Id==cs.Id) + .ToDictionary(it => it.Id, it => it.Name); + + var test21 = db.Queryable().Where(it=>it.Id.ToString()==1.ToString()).Select(it => it.CreateTime.ToString("24")).First(); + Console.WriteLine("#### Examples End ####"); + } + + private static void ReturnType() + { + Console.WriteLine(""); + Console.WriteLine("#### ReturnType Start ####"); + var db = GetInstance(); + List list = db.Queryable().ToList(); + + var x2=db.Ado.SqlQueryAsync("select * from [Order] "); + x2.Wait(); + var x22 = db.Ado.GetScalarAsync("select * from [Order] "); + x22.Wait(); + var x222 = db.Ado.ExecuteCommandAsync("select * from [Order] "); + x222.Wait(); + Order item = db.Queryable().First(it => it.Id == 1); + + DataTable dataTable = db.Queryable().Select(it => it.Id).ToDataTable(); + + var json = db.Queryable().ToJson(); + + List listInt = db.Queryable().Select(it => it.Id).ToList(); + + var dynamic = db.Queryable().Select().ToList(); + + var viewModel = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId , + JoinType.Left, o.CustomId == c.Id + )) + .Select().ToList(); + + var newDynamic = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => new { orderName = o.Name, cusName=c.Name }).ToList(); + + var newClass = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => new ViewOrder { Name=o.Name, CustomName=c.Name }).ToList(); + + + var oneClass = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => c).ToList(); + + var twoClass = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select((o, i, c) => new { o,i}).ToList(); + + List> ListDic = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, o.CustomId == c.Id + )) + .Select().ToList().Select(it => it.ToDictionary(x => x.Key, x => x.Value)).ToList(); + Console.WriteLine("#### ReturnType End ####"); + } + + private static void Subquery() + { + Console.WriteLine(""); + Console.WriteLine("#### Subquery Start ####"); + var db = GetInstance(); + + var list = db.Queryable().Take(10).Select(it => new + { + customName=SqlFunc.Subqueryable().Where("it.CustomId=id").Select(s=>s.Name), + customName2 = SqlFunc.Subqueryable().Where("it.CustomId = id").Where(s => true).Select(s => s.Name) + }).ToList(); + + var list1 = db.Queryable().Select(it => new + { + id = SqlFunc.Subqueryable().Where(s => s.Id == 1).Sum(s => s.Id) * 1 + }).ToList(); + + var list2 = db.Queryable().Where(it => + SqlFunc.Subqueryable() + .LeftJoin((i,z)=>i.ItemId==z.ItemId) + .InnerJoin((i,z,y) => i.ItemId == z.ItemId) + .InnerJoin((i,z,y,h) => i.ItemId == z.ItemId) + .InnerJoin((i, z, y, h, n) => i.ItemId == z.ItemId) + .Where((i, z) => i.ItemId == z.ItemId) + .Any() + ).ToList(); + + var list3 = db.Queryable().Select(it => new + { + customName = SqlFunc.Subqueryable().Where(s=>s.Id==it.CustomId).GroupBy(s=>s.Name).Having(s=>SqlFunc.AggregateCount(s.Id)>0).Select(s => s.Name) + }).ToList(); + + + var exp = Expressionable.Create().And(s => s.Id==1).ToExpression(); + var list4 = db.Queryable().Select(it => new + { + customName = SqlFunc.Subqueryable().Where(exp).Where(exp).GroupBy(s => s.Name).Having(s => SqlFunc.AggregateCount(s.Id) > 0).Select(s => s.Name) + }).ToList(); + + + var list5 = db.Queryable().Where(it => + SqlFunc.Subqueryable() + .LeftJoin((i, y) => i.ItemId == y.ItemId) + .InnerJoin((i, z) => i.ItemId == z.ItemId) + .Where(i => i.ItemId == 1) + .Any() + ).ToList(); + Console.WriteLine("#### Subquery End ####"); + } + + private static void SqlFuncTest() + { + Console.WriteLine(""); + Console.WriteLine("#### SqlFunc Start ####"); + var db = GetInstance(); + var index= db.Queryable().Select(it => SqlFunc.CharIndex("a", "cccacc")).First(); + var list = db.Queryable().Select(it =>new ViewOrder() + { + + Id = SqlFunc.AggregateSum(SqlFunc.IF(it.Id > 0).Return(1).End(0)) + }).ToList(); + var list2 = db.Queryable().Where(it=>it.CreateTime.Date==it.CreateTime).Select(it => new + { + date = it.CreateTime.Date, + datetime = DateTime.Now.Date + }).ToList(); + Console.WriteLine("#### SqlFunc End ####"); + } + + private static void Mapper() + { + Console.WriteLine(""); + Console.WriteLine("#### Mapper Start ####"); + var db = GetInstance(); + //Creater Table + db.CodeFirst.InitTables(typeof(Tree)); + db.DbMaintenance.TruncateTable("tree"); + db.Insertable(new Tree() { Id = 1, Name = "root" }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 11, Name = "child1",ParentId=1 }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 12, Name = "child2",ParentId=1 }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 2, Name = "root" }).ExecuteCommand(); + db.Insertable(new Tree() { Id = 22, Name = "child3", ParentId = 2 }).ExecuteCommand(); + + // Same property name mapping,Both entities have parentId + var list = db.Queryable().Mapper(it => it.Parent, it => it.ParentId).ToList(); + + + //If both entities have parentId, I don't want to associate with parentId. + var list1 =db.Queryable() + //parent=(select * from parent where id=it.parentid) + .Mapper(it=>it.Parent,it=>it.ParentId, it=>it.Parent.Id) + //Child=(select * from parent where ParentId=it.id) + .Mapper(it => it.Child, it => it.Id, it => it.Parent.ParentId) + .ToList(); + + + db.Insertable(new Tree() { Id = 222, Name = "child11", ParentId = 11 }).ExecuteCommand(); + var tree = db.Queryable().ToTree(it => it.Child, it => it.ParentId, 0); + var allchilds= db.Queryable().ToChildList(it => it.ParentId, 0); + var allchilds1 = db.Queryable().ToChildList(it => it.ParentId, 1); + var allchilds2= db.Queryable().ToChildList(it => it.ParentId, 2); + var parentList = db.Queryable().ToParentList(it => it.ParentId, 22); + var parentList2 = db.Queryable().ToParentList(it => it.ParentId, 222); + var parentList3 = db.Queryable().ToParentList(it => it.ParentId, 2); + + //one to one + var list2 = db.Queryable().Mapper(it => it.Order, it => it.OrderId).ToList(); + + //one to many + var list3 = db.Queryable().Mapper(it => it.Items, it => it.Items.First().OrderId).ToList(); + + //many to many + db.CodeFirst.InitTables(); + + db.Insertable(new A() { Name = "A" }).ExecuteCommand(); + db.Insertable(new B() { Name = "B" }).ExecuteCommand(); + db.Insertable(new ABMapping() { AId = 1, BId = 1 }).ExecuteCommand(); + + var list4 = db.Queryable() + .Mapper(it => it.A, it => it.AId) + .Mapper(it => it.B, it => it.BId).ToList(); + + //Manual mode + var result = db.Queryable().Take(10).Select().Mapper((itemModel, cache) => + { + var allItems = cache.Get(orderList => { + var allIds = orderList.Select(it => it.Id).ToList(); + return db.Queryable().Where(it => allIds.Contains(it.OrderId)).ToList();//Execute only once + }); + itemModel.Items = allItems.Where(it => it.OrderId==itemModel.Id).ToList();//Every time it's executed + }).ToList(); + + Console.WriteLine("#### End Start ####"); + } + + private static void NoEntity() + { + Console.WriteLine(""); + Console.WriteLine("#### No Entity Start ####"); + var db = GetInstance(); + + var list = db.Queryable().AS("order ").Where("id=id", new { id = 1 }).ToList(); + + var list2 = db.Queryable("o").AS("order").AddJoinInfo("OrderDetail", "i", "o.id=i.OrderId").Where("id=id", new { id = 1 }).Select("o.*").ToList(); + Console.WriteLine("#### No Entity End ####"); + } + + private static void JoinTable() + { + Console.WriteLine(""); + Console.WriteLine("#### Join Table Start ####"); + var db = GetInstance(); + + //Simple join + var list = db.Queryable((o, i, c) => o.Id == i.OrderId&&c.Id == o.CustomId) + .Select() + .ToList(); + + //Join table + var list2 = db.Queryable((o, i, c) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId, + JoinType.Left, c.Id == o.CustomId + )) + .Select().ToList(); + + //Join queryable + var query1 = db.Queryable((o, i) => new JoinQueryInfos( + JoinType.Left, o.Id == i.OrderId + )) + .Where(o => o.Name == "jack"); + + var query2 = db.Queryable(); + var list3=db.Queryable(query1, query2,JoinType.Left, (p1, p2) => p1.CustomId == p2.Id).Select().ToList(); + + + var query3 = db.Union( + db.Queryable().Where(it => it.Name.Contains("a")), + db.Queryable().Where(it => it.Name.Contains("b")) + ).ToList(); + + + + var query4 = db.Queryable( + db.Queryable().Where(it => it.Name.Contains("a")), + db.Queryable().Where(it => it.CreateTime>DateTime.Now), + db.Queryable().Where(it => it.Name.Contains("b")), + JoinType.Left, (o, i, c) => o.Id==i.OrderId, + JoinType.Left,(o,i,c)=>o.CustomId==c.Id + + ).Select(o=>o).ToList(); + + + var query5 = db.Queryable() + .InnerJoin((o, cus) => o.CustomId == cus.Id) + .InnerJoin((o, cus, oritem) => o.Id == oritem.OrderId) + .Where((o) => o.Id == 1) + .Select((o, cus) => new ViewOrder { Id=o.Id, CustomName = cus.Name }) + .ToList(); + + var query6 = db.Queryable(db.Queryable()).LeftJoin((m, i) => m.Id == i.OrderId) + .ToList(); + + + var query7 = db.Queryable(db.Queryable().Select().MergeTable()).LeftJoin((m, i) => m.Id == i.OrderId) + .ToList(); + + + var query8 = db.Queryable() + .LeftJoin(db.Queryable().Where(it=>it.Id==1),(o,i)=>o.CustomId==i.Id) + .LeftJoin(db.Queryable().Where(it=>it.OrderId==2),(o,i,item)=>item.OrderId==o.Id) + .LeftJoin(db.Queryable().Where(it => it.Id >0), (o, i, item, od) => od.Id == o.Id) + .Select(o => o).ToList(); + + Console.WriteLine("#### Join Table End ####"); + } + + private static void QueryConditions() + { + Console.WriteLine(""); + Console.WriteLine("#### Query Conditions Start ####"); + + SqlSugarClient db = GetInstance(); + + /*** By expression***/ + + //id=@id + var list = db.Queryable().Where(it => it.Id == 1).ToList(); + //id=@id or name like '%'+@name+'%' + var list2 = db.Queryable().Where(it => it.Id == 1 || it.Name.Contains("jack")).ToList(); + + + //Create expression + var exp = Expressionable.Create() + .And(it => it.Id == 1) + .Or(it => it.Name.Contains("jack")).ToExpression(); + var list3 = db.Queryable().Where(exp).ToList(); + + + /*** By sql***/ + + //id=@id + var list4 = db.Queryable().Where("id=@id", new { id = 1 }).ToList(); + //id=@id or name like '%'+@name+'%' + var list5 = db.Queryable().Where("id=@id or name like '%'+@name+'%' ", new { id = 1, name = "jack" }).ToList(); + + + + /*** By dynamic***/ + + //id=1 + var conModels = new List(); + conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1 + var student = db.Queryable().Where(conModels).ToList(); + + //Complex use case + List Order = new List(); + conModels.Add(new ConditionalModel() { FieldName = "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 list6 = db.Queryable().Where(conModels).ToList(); + + /*** Conditional builder ***/ + + // use whereif + string name = ""; + int id = 1; + var query = db.Queryable() + .WhereIF(!string.IsNullOrEmpty(name), it => it.Name.Contains(name)) + .WhereIF(id > 0, it => it.Id == id).ToList(); + //clone new Queryable + var query2 = db.Queryable().Where(it => it.Id == 1); + var list7 = query2.Clone().Where(it => it.Name == "jack").ToList();//id=1 and name = jack + var list8 = query2.Clone().Where(it => it.Name == "tom").ToList();//id=1 and name = tom + + Console.WriteLine("#### Condition Screening End ####"); + + + + } + + private static void Async() + { + Console.WriteLine(""); + Console.WriteLine("#### Async Start ####"); + + SqlSugarClient db = GetInstance(); + var task1 = db.Queryable().FirstAsync(); + task1.Wait(); + var task2 = db.Queryable().Where(it => it.Id == 1).ToListAsync(); + + + task2.Wait(); + + Console.WriteLine("#### Async End ####"); + } + + private static SqlSugarClient GetInstance() + { + return new SqlSugarClient(new ConnectionConfig() + { + DbType = SqlSugar.DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo2_Updateable.cs b/Src/Asp.Net/AccessTest/Demo/Demo2_Updateable.cs new file mode 100644 index 000000000..9758199c6 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo2_Updateable.cs @@ -0,0 +1,118 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo2_Updateable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Updateable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + + + /*** 1.entity or List ***/ + + var updateObj = new Order() { Id = 1, Name = "order1" }; + var updateObjs = new List { + new Order() { Id = 11, Name = "order11" }, + new Order() { Id = 12, Name = "order12" } + }; + + //update all columns by primary key + var result = db.Updateable(updateObj).ExecuteCommand();//update single + var result2 = db.Updateable(updateObjs).ExecuteCommand();//update List + + //Ignore Name and Price + var result3 = db.Updateable(updateObj).IgnoreColumns(it => new { it.CreateTime, it.Price }).ExecuteCommand(); + + //only update Name and CreateTime + var result4 = db.Updateable(updateObj).UpdateColumns(it => new { it.Name, it.CreateTime }).ExecuteCommand(); + + //If there is no primary key + var result5 = db.Updateable(updateObj).WhereColumns(it => new { it.Id }).ExecuteCommand();//update single by id + var result6 = db.Updateable(updateObjs).WhereColumns(it => new { it.Id }).ExecuteCommand();//update List by id + + //Re set value + var result66 = db.Updateable(new List { updateObj }).ReSetValue(it => it.Id = 112).IgnoreColumns(it => new { it.CreateTime, it.Price }).ExecuteCommand(); + + + + /*** 2.by expression ***/ + + //update name,createtime + var result7 = db.Updateable(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand(); + var result71 = db.Updateable().SetColumns(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand(); + //only update name + var result8 = db.Updateable(it => it.Name == "Name" + "1").Where(it => it.Id == 1).ExecuteCommand(); + var result81 = db.Updateable().SetColumns(it => it.Name == "Name" + "1").Where(it => it.Id == 1).ExecuteCommand(); + // + + + + + /*** 3.by Dictionary ***/ + var dt = new Dictionary(); + dt.Add("id", 1); + dt.Add("name", "abc"); + dt.Add("createTime", DateTime.Now); + var dtList = new List>(); + dtList.Add(dt); + + var t66 = db.Updateable(dt).AS("[Order]").WhereColumns("id").ExecuteCommand(); + var t666 = db.Updateable(dtList).AS("[Order]").WhereColumns("id").ExecuteCommand(); + + + + /*** 4.Other instructions ***/ + + var caseValue = "1"; + //Do not update NULL columns + db.Updateable(updateObj).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); + + //if 1 update name else if 2 update name,createtime + db.Updateable(updateObj) + .UpdateColumnsIF(caseValue == "1", it => new { it.Name }) + .UpdateColumnsIF(caseValue == "2", it => new { it.Name, it.CreateTime }) + .ExecuteCommand(); + //Use Lock + db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand(); + + //Where Sql + //db.Updateable(updateObj).Where("id=@x", new { x = "1" }).ExecuteCommand(); + + + var levelCode = "123213123131321"; + db.Updateable(a => a.Name == "a") + .Where(a => SqlFunc.StartsWith(a.Name, levelCode)) + .AddQueue(); + db.SaveQueues(); + + var dataTable = db.Queryable().Select("id,name,1 as price").Take(2).ToDataTable(); + db.Fastest().BulkUpdate("Order", dataTable,new string[] {"id" },new string[] {"name" }); + Console.WriteLine("#### Updateable End ####"); + } + + } +} \ No newline at end of file diff --git a/Src/Asp.Net/AccessTest/Demo/Demo3_Insertable.cs b/Src/Asp.Net/AccessTest/Demo/Demo3_Insertable.cs new file mode 100644 index 000000000..2121047a8 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo3_Insertable.cs @@ -0,0 +1,331 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo3_Insertable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Insertable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + var insertObj = new Order() { Id = 1, Name = "order1", Price = 0 }; + var insertObjs = new List { + new Order() { Id = 11, Name = "XX", Price=0 }, + new Order() { Id = 12, Name = "XX2" , Price=0} + }; + + var x=db.Insertable(insertObjs).RemoveDataCache().IgnoreColumns(it=>it.CreateTime).UseParameter().ExecuteCommand(); + + //Ignore CreateTime + db.Insertable(insertObj).IgnoreColumns(it => new { it.CreateTime }).ExecuteReturnIdentity();//get identity + db.Insertable(insertObj).IgnoreColumns("CreateTime").ExecuteReturnIdentity(); + + //Only insert Name and Price + db.Insertable(insertObj).InsertColumns(it => new { it.Name, it.Price }).ExecuteReturnIdentity(); + db.Insertable(insertObj).InsertColumns("Name", "Price").ExecuteReturnIdentity(); + + //ignore null columns + db.Insertable(insertObjs).ExecuteCommand();//get change row count + + //Use Lock + db.Insertable(insertObj).With(SqlWith.UpdLock).ExecuteCommand(); + + insertObjs = new List { + new Order() { Id = 11, Name = "order11", Price=1 }, + new Order() { Id = 12, Name = "order12" , Price=20, CreateTime=DateTime.Now, CustomId=1} + }; + db.Insertable(insertObjs).UseSqlServer().ExecuteBulkCopy(); + var dt = db.Queryable().Take(5).ToDataTable(); + dt.TableName = "Order"; + db.Insertable(dt).UseSqlServer().ExecuteBulkCopy(); + db.CodeFirst.InitTables(); + db.CodeFirst.InitTables(); + db.DbMaintenance.TruncateTable("RootTable0"); + db.DbMaintenance.TruncateTable("TwoItem"); + db.DbMaintenance.TruncateTable("TwoItem2"); + db.DbMaintenance.TruncateTable("TwoItem3"); + db.DbMaintenance.TruncateTable("ThreeItem2"); + Console.WriteLine("SubInsert Start"); + + db.Insertable(new Order() + { + Name = "订单 1", + CustomId = 1, + Price = 100, + CreateTime = DateTime.Now, + Id = 0, + Items = new List() { + new OrderItem(){ + CreateTime=DateTime.Now, + OrderId=0, + Price=1, + ItemId=1 + }, + new OrderItem(){ + CreateTime=DateTime.Now, + OrderId=0, + Price=2, + ItemId=2 + } + } + }) + .AddSubList(it => it.Items.First().OrderId).ExecuteCommand(); + + + + db.Insertable(new List() { + new RootTable0() + { + Name="aa", + TwoItem2=new TwoItem2() { + Id="1", + ThreeItem2=new List(){ + new ThreeItem2(){ Name="a", TwoItem2Id="1" }, + new ThreeItem2(){ Id=2, Name="a2", TwoItem2Id="2" } + } + }, + TwoItem=new TwoItem() + { + Name ="itema" , + RootId=2 + }, + TwoItem3=new List(){ + new TwoItem3(){ Id=0, Name="a",Desc="" }, + + } + }, + new RootTable0() + { + Name="bb", + TwoItem2=new TwoItem2() { + Id="2" + }, + TwoItem=new TwoItem() + { + Name ="itemb" , + RootId=2, + + }, + TwoItem3=new List(){ + new TwoItem3(){ Id=1, Name="b",Desc="" }, + new TwoItem3(){ Id=2, Name="b1",Desc="1" }, + } + } + }) + .AddSubList(it => it.TwoItem.RootId) + .AddSubList(it => new SubInsertTree() + { + Expression = it.TwoItem2.RootId, + ChildExpression = new List() { + new SubInsertTree(){ + Expression=it.TwoItem2.ThreeItem2.First().TwoItem2Id + } + } + }) + .AddSubList(it => it.TwoItem3) + .ExecuteCommand(); + + SubNoIdentity(db); + SubIdentity(db); + + + var dict = new Dictionary(); + dict.Add("name", "1"); + dict.Add("CreateTime", DateTime.Now); + dict.Add("Price", 1); + db.Insertable(dict).AS("[Order]").ExecuteCommand(); + + + db.Fastest().BulkCopy(insertObjs); + + + var dataTable= db.Queryable().Select("id,name,Price").Take(2).ToDataTable(); + int result= db.Fastest().BulkCopy("order", dataTable); + Console.WriteLine("#### Insertable End ####"); + + } + + private static void SubNoIdentity(SqlSugarClient db) + { + db.CodeFirst.InitTables(); + db.DbMaintenance.TruncateTable("Country"); + db.DbMaintenance.TruncateTable("Province"); + db.DbMaintenance.TruncateTable("City"); + db.Insertable(new List() + { + new Country(){ + Id=1, + Name="中国", + Provinces=new List(){ + new Province{ + Id=1001, + Name="江苏", + citys=new List(){ + new City(){ Id=1001001, Name="南通" }, + new City(){ Id=1001002, Name="南京" } + } + }, + new Province{ + Id=1002, + Name="上海", + citys=new List(){ + new City(){ Id=1002001, Name="徐汇" }, + new City(){ Id=1002002, Name="普陀" } + } + }, + new Province{ + Id=1003, + Name="北京", + citys=new List(){ + new City(){ Id=1003001, Name="北京A" }, + new City(){ Id=1003002, Name="北京B" } + } + } + } + }, + new Country(){ + Name="美国", + Id=2, + Provinces=new List() + { + new Province(){ + Name="美国小A", + Id=20001 + }, + new Province(){ + Name="美国小b", + Id=20002 + } + } + }, + new Country(){ + Name="英国", + Id=3 + } + }) + .AddSubList(it => new SubInsertTree() + { + Expression = it.Provinces.First().CountryId, + ChildExpression = new List() { + new SubInsertTree(){ + Expression=it.Provinces.First().citys.First().ProvinceId + } + } + }) + .ExecuteCommand(); + + var list = db.Queryable() + .Mapper(it => it.Provinces, it => it.Provinces.First().CountryId) + .Mapper(it => + { + foreach (var item in it.Provinces) + { + item.citys = db.Queryable().Where(y => y.ProvinceId == item.Id).ToList(); + } + }) + .ToList(); + } + private static void SubIdentity(SqlSugarClient db) + { + db.CodeFirst.InitTables(); + db.DbMaintenance.TruncateTable("Country1"); + db.DbMaintenance.TruncateTable("Province1"); + db.DbMaintenance.TruncateTable("City1"); + db.Insertable(new List() + { + new Country1(){ + Id=1, + Name="中国", + Provinces=new List(){ + new Province1{ + Id=1001, + Name="江苏", + citys=new List(){ + new City1(){ Id=1001001, Name="南通" }, + new City1(){ Id=1001002, Name="南京" } + } + }, + new Province1{ + Id=1002, + Name="上海", + citys=new List(){ + new City1(){ Id=1002001, Name="徐汇" }, + new City1(){ Id=1002002, Name="普陀" } + } + }, + new Province1{ + Id=1003, + Name="北京", + citys=new List(){ + new City1(){ Id=1003001, Name="北京A" }, + new City1(){ Id=1003002, Name="北京B" } + } + } + } + }, + new Country1(){ + Name="美国", + Id=2, + Provinces=new List() + { + new Province1(){ + Name="美国小A", + Id=20001 + }, + new Province1(){ + Name="美国小b", + Id=20002 + } + } + }, + new Country1(){ + Name="英国", + Id=3 + } + }) + .AddSubList(it => new SubInsertTree() + { + Expression = it.Provinces.First().CountryId, + ChildExpression = new List() { + new SubInsertTree(){ + Expression=it.Provinces.First().citys.First().ProvinceId + } + } + }) + .ExecuteCommand(); + + var list = db.Queryable() + .Mapper(it => it.Provinces, it => it.Provinces.First().CountryId) + .Mapper(it => + { + foreach (var item in it.Provinces) + { + item.citys = db.Queryable().Where(y => y.ProvinceId == item.Id).ToList(); + } + }) + .ToList(); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo4_Deleteable.cs b/Src/Asp.Net/AccessTest/Demo/Demo4_Deleteable.cs new file mode 100644 index 000000000..9736890b9 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo4_Deleteable.cs @@ -0,0 +1,59 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo4_Deleteable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Deleteable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + //by entity + db.Deleteable().Where(new Order() { Id = 1111 }).ExecuteCommand(); + + //by primary key + db.Deleteable().In(1111).ExecuteCommand(); + + //by primary key array + db.Deleteable().In(new int[] { 1111, 2222 }).ExecuteCommand(); + + //by expression + db.Deleteable().Where(it => it.Id == 11111).ExecuteCommand(); + + //logic delete + db.CodeFirst.InitTables(); + ; + db.Deleteable().Where(it=>it.Id==1).IsLogic().ExecuteCommand(); + Console.WriteLine("#### Deleteable End ####"); + + } + } + public class LogicTest + { + [SugarColumn(IsPrimaryKey =true,IsIdentity =true)] + public int Id { get; set; } + + public bool isdeleted { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo5_SqlQueryable.cs b/Src/Asp.Net/AccessTest/Demo/Demo5_SqlQueryable.cs new file mode 100644 index 000000000..eb1a4bc6f --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo5_SqlQueryable.cs @@ -0,0 +1,36 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo5_SqlQueryable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### SqlQueryable Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + + int total = 0; + var list = db.SqlQueryable("select * from [order]").ToPageList(1, 2, ref total); + + + //by expression + var list2 = db.SqlQueryable("select * from [order]").Where(it => it.Id == 1).ToPageList(1, 2); + //by sql + var list3 = db.SqlQueryable("select * from [order]").Where("id=@id", new { id = 1 }).ToPageList(1, 2); + + Console.WriteLine("#### SqlQueryable End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo6_Queue.cs b/Src/Asp.Net/AccessTest/Demo/Demo6_Queue.cs new file mode 100644 index 000000000..cbd4675c4 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo6_Queue.cs @@ -0,0 +1,53 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo6_Queue + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Queue Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + db.Insertable(new Order() { Name = "a" }).AddQueue(); + db.Insertable(new Order() { Name = "b" }).AddQueue(); + db.SaveQueues(); + + + db.Insertable(new Order() { Name = "a" }).AddQueue(); + db.Insertable(new Order() { Name = "b" }).AddQueue(); + db.Insertable(new Order() { Name = "c" }).AddQueue(); + db.Insertable(new Order() { Name = "d" }).AddQueue(); + var ar = db.SaveQueuesAsync(); + ar.Wait(); + + db.Queryable().AddQueue(); + db.Queryable().AddQueue(); + db.AddQueue("select * from [Order] where id=@id", new { id = 10000 }); + db.AddQueue("select id=@id+1", new { id = 10000 }); + var result2 = db.SaveQueues(); + + Console.WriteLine("#### Queue End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo7_Ado.cs b/Src/Asp.Net/AccessTest/Demo/Demo7_Ado.cs new file mode 100644 index 000000000..88b7b678a --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo7_Ado.cs @@ -0,0 +1,78 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo7_Ado + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Ado Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + //sql + var dt = db.Ado.GetDataTable("select * from [order] where @id>0 or name=@name", new List(){ + new SugarParameter("@id",1), + new SugarParameter("@name","2") + }); + + //sql + var dt2 = db.Ado.GetDataTable("select * from [order] where @id>0 or name=@name", new { id = 1, name = "2" }); + + + //create sp + db.Ado.ExecuteCommand(@" + if object_id('up_user') is not null + drop proc up_user;"); + db.Ado.ExecuteCommand(@" + create proc up_user + @id int, + @name varchar(10) ='' output + as + + begin + set @name='abc' + select @id as id + end + "); + //get output + var dt3 = db.Ado.UseStoredProcedure().GetDataTable("up_user", new { name = "张三", id = 0 }); + var IdP = new SugarParameter("@id", 1); + var NameP = new SugarParameter("@name", null, true);//isOutput=true + var dt4 = db.Ado.UseStoredProcedure().GetDataTable("up_user", IdP, NameP); + var outputValue = NameP.Value; + + + //There are many methods to under db.ado + var list = db.Ado.SqlQuery("select * from [order] "); + var list2 = db.Ado.SqlQuery("select * from [order] where 1=2;select * from [order] "); + var list3 = db.Ado.SqlQuery(" delete from [order] where 2=15 "); + var intValue = db.Ado.SqlQuerySingle("select 1"); + db.Ado.ExecuteCommand("delete [order] where id>1000"); + + db.SqlQueryable(@"select * +from custom").ToList(); + //db.Ado.xxx + Console.WriteLine("#### Ado End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo8_Saveable.cs b/Src/Asp.Net/AccessTest/Demo/Demo8_Saveable.cs new file mode 100644 index 000000000..82c44f685 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo8_Saveable.cs @@ -0,0 +1,69 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo8_Saveable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Saveable Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + + //insert or update + var x= db.Storageable(new Order() { Id=1, Name="jack" }).ToStorage(); + x.AsUpdateable.ExecuteCommand(); + x.AsInsertable.ExecuteCommand(); + + + var x2 = db.Storageable(new Order() { Id = 0, Name = "jack" }).ToStorage(); + x2.BulkCopy(); + x2.BulkUpdate(); + + var dt = db.Queryable().Take(1).ToDataTable(); + dt.TableName = "order"; + var addRow = dt.NewRow(); + addRow["id"] = 0; + addRow["price"] = 1; + addRow["Name"] = "a"; + dt.Rows.Add(addRow); + var x3 = + db.Storageable(dt) + .WhereColumns("id").ToStorage(); + + x3.AsInsertable.IgnoreColumns("id").ExecuteCommand(); + x3.AsUpdateable.ExecuteCommand(); + + + var x4 = + db.Storageable(dt) + .SplitDelete(it=>Convert.ToInt32( it["id"])>0) + .WhereColumns("id").ToStorage(); + x4.AsDeleteable.ExecuteCommand(); + + Console.WriteLine(""); + Console.WriteLine("#### Saveable End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Demo9_EntityMain.cs b/Src/Asp.Net/AccessTest/Demo/Demo9_EntityMain.cs new file mode 100644 index 000000000..be795b098 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Demo9_EntityMain.cs @@ -0,0 +1,46 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Demo9_EntityMain + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### EntityMain Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + var entityInfo = db.EntityMaintenance.GetEntityInfo(); + foreach (var column in entityInfo.Columns) + { + Console.WriteLine(column.DbColumnName); + } + + var dbColumnsName = db.EntityMaintenance.GetDbColumnName("Name"); + + var dbTableName = db.EntityMaintenance.GetTableName(); + + //more https://github.com/sunkaixuan/SqlSugar/wiki/9.EntityMain + Console.WriteLine("#### EntityMain End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoA_DbMain.cs b/Src/Asp.Net/AccessTest/Demo/DemoA_DbMain.cs new file mode 100644 index 000000000..206cd6507 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoA_DbMain.cs @@ -0,0 +1,42 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoA_DbMain + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### DbMain Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + var tables = db.DbMaintenance.GetTableInfoList(); + foreach (var table in tables) + { + Console.WriteLine(table.Description); + } + //more https://github.com/sunkaixuan/SqlSugar/wiki/a.DbMain + Console.WriteLine("#### DbMain End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoB_Aop.cs b/Src/Asp.Net/AccessTest/Demo/DemoB_Aop.cs new file mode 100644 index 000000000..dfd332c46 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoB_Aop.cs @@ -0,0 +1,77 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoB_Aop + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Aop Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + db.Aop.OnLogExecuted = (sql, pars) => //SQL executed event + { + Console.WriteLine("OnLogExecuted"+sql); + }; + db.Aop.OnLogExecuting = (sql, pars) => //SQL executing event (pre-execution) + { + Console.WriteLine("OnLogExecuting" + sql); + }; + db.Aop.OnError = (exp) =>//SQL execution error event + { + //exp.sql + }; + db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL executing event (pre-execution,SQL script can be modified) + { + return new KeyValuePair(sql, pars); + }; + db.Aop.OnDiffLogEvent = it =>//Get data changes + { + var editBeforeData = it.BeforeData; + var editAfterData = it.AfterData; + var sql = it.Sql; + var parameter = it.Parameters; + var businessData = it.BusinessData; + var time = it.Time; + var diffType = it.DiffType;//enum insert 、update and delete + Console.WriteLine(businessData); + //Write logic + }; + + + var list= db.Queryable().ToList(); + db.Queryable().ToList(); + + //OnDiffLogEvent + var data = db.Queryable().First(); + + db.Insertable(list.Take(5).ToList()).EnableDiffLogEvent().ExecuteCommand(); + + db.Insertable(new Order() { CreateTime=DateTime.Now, CustomId=1, Name="a" ,Price=1 }).EnableDiffLogEvent().ExecuteCommand(); + + data.Name = "changeName"; + db.Updateable(data).EnableDiffLogEvent("--update Order--").ExecuteCommand(); + + db.Updateable(list.Take(5).ToList()).EnableDiffLogEvent("--update Order--").ExecuteCommand(); + + + db.Updateable().SetColumns(it=>it.Name=="asdfa").Where(it=>it.Id==1).EnableDiffLogEvent("--update Order--").ExecuteCommand(); + + db.Updateable().SetColumns(it => it.Name == "asdfa") + .Where(it =>SqlFunc.Subqueryable().Where(x=>x.Id==it.Id).Any()).EnableDiffLogEvent("--update Order--").ExecuteCommand(); + Console.WriteLine("#### Aop End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoD_DbFirst.cs b/Src/Asp.Net/AccessTest/Demo/DemoD_DbFirst.cs new file mode 100644 index 000000000..db57e0938 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoD_DbFirst.cs @@ -0,0 +1,75 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public class DemoD_DbFirst + { + public static void Init() + { + Console.WriteLine(); + Console.WriteLine("#### DbFirst Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + + db.DbFirst.CreateClassFile("c:\\Demo\\1", "Models"); + + + db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2", "Models"); + + + db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\3", "Models"); + + + db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\4", "Models"); + + + db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\5", "Models"); + + + db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\Demo\\6", "Demo.Models"); + + + 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:\\Demo\\7"); + + + + foreach (var item in db.DbMaintenance.GetTableInfoList()) + { + string entityName = item.Name.ToUpper();/*Format class name*/ + db.MappingTables.Add(entityName , item.Name); + foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name)) + { + db.MappingColumns.Add(col.DbColumnName.ToUpper() /*Format class property name*/, col.DbColumnName, entityName); + } + } + db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\8", "Models"); + + + //Use Razor Template + //db.DbFirst.UseRazorAnalysis(RazorFirst.DefaultRazorClassTemplate).CreateClassFile(""); + + Console.WriteLine("#### DbFirst End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoE_CodeFirst.cs b/Src/Asp.Net/AccessTest/Demo/DemoE_CodeFirst.cs new file mode 100644 index 000000000..8692517e1 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoE_CodeFirst.cs @@ -0,0 +1,40 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public class DemoE_CodeFirst + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### CodeFirst Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString3, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + db.DbMaintenance.CreateDatabase(); + db.CodeFirst.InitTables(typeof(CodeFirstTable1));//Create CodeFirstTable1 + db.Insertable(new CodeFirstTable1() { Name = "a", Text="a" }).ExecuteCommand(); + var list = db.Queryable().ToList(); + Console.WriteLine("#### CodeFirst end ####"); + } + } + + public class CodeFirstTable1 + { + [SugarColumn(IsIdentity = true, IsPrimaryKey = true)] + public int Id { get; set; } + public string Name { get; set; } + [SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom + public string Text { get; set; } + [SugarColumn(IsNullable = true)] + public DateTime CreateTime { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoF_Utilities.cs b/Src/Asp.Net/AccessTest/Demo/DemoF_Utilities.cs new file mode 100644 index 000000000..7db24c350 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoF_Utilities.cs @@ -0,0 +1,46 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoF_Utilities + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Utilities Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + + + List ids = Enumerable.Range(1, 100).ToList(); + db.Utilities.PageEach(ids, 10, list => + { + Console.WriteLine(string.Join("," ,list)); + }); + + var list2= db.Utilities.DataTableToList(db.Ado.GetDataTable("select * from [order]")); + + //more https://github.com/sunkaixuan/SqlSugar/wiki/f.Utilities + Console.WriteLine("#### Utilities End ####"); + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoG_SimpleClient.cs b/Src/Asp.Net/AccessTest/Demo/DemoG_SimpleClient.cs new file mode 100644 index 000000000..dc278f68b --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoG_SimpleClient.cs @@ -0,0 +1,64 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoG_SimpleClient + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### SimpleClient Start ####"); + + var order = new OrderDal(); + order.GetList(); + order.GetById(1); + order.MyTest(); + Console.WriteLine("#### SimpleClient End ####"); + } + public class OrderDal:Repository + { + public void MyTest() + { + base.CommQuery("1=1"); + base.ChangeRepository>().CommQuery("1=1"); + } + } + public class Repository : SimpleClient where T : class, new() + { + public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null + { + if (context == null) + { + var db = new SqlSugarClient(new ConnectionConfig() + { + DbType = SqlSugar.DbType.SqlServer, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + ConnectionString = Config.ConnectionString + }); + base.Context = db; + db.Aop.OnLogExecuting = (s, p) => + { + Console.WriteLine(s); + }; + } + } + + /// + /// 扩展方法,自带方法不能满足的时候可以添加新方法 + /// + /// + public List CommQuery(string sql) + { + //base.Context.Queryable().ToList();可以拿到SqlSugarClient 做复杂操作 + return base.Context.Queryable().Where(sql).ToList(); + } + + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoH_Tenant.cs b/Src/Asp.Net/AccessTest/Demo/DemoH_Tenant.cs new file mode 100644 index 000000000..16fdd3826 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoH_Tenant.cs @@ -0,0 +1,82 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoH_Tenant + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### DemoH_Tenant Start ####"); + new C1Service().Test(); + Console.WriteLine("#### DemoH_Tenant End ####"); + } + public class C1Service : Repository + { + public void Test() + { + db.BeginTran(); + base.GetList(); //调用内部仓储方法 + base.ChangeRepository>().GetList();//调用外部仓储 + db.CommitTran(); + } + } + public class Repository : SimpleClient where T : class, new() + { + //单例实同db同上下文共享 + public static SqlSugarScope db = new SqlSugarScope(new List { + new ConnectionConfig() + { + ConfigId="1", + DbType = SqlSugar.DbType.SqlServer, + IsAutoCloseConnection = true, + ConnectionString = Config.ConnectionString + }, + new ConnectionConfig() + { + ConfigId="2", + DbType = SqlSugar.DbType.SqlServer, + IsAutoCloseConnection = true, + ConnectionString = Config.ConnectionString2 + } + }); + public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null + { + if (context == null) + { + var configId = typeof(T).GetCustomAttribute().configId; + Context = db.GetConnection(configId); + Context.CodeFirst.InitTables(); + } + } + + /// + /// 扩展方法,自带方法不能满足的时候可以添加新方法 + /// + /// + public List CommQuery(string sql) + { + //base.Context.Queryable().ToList();可以拿到SqlSugarClient 做复杂操作 + return base.Context.Queryable().Where(sql).ToList(); + } + + } + + [TenantAttribute("1")] + public class C1Table + { + public string Id { get; set; } + } + [TenantAttribute("2")] + public class C2Table + { + public string Id { get; set; } + } + } +} \ No newline at end of file diff --git a/Src/Asp.Net/AccessTest/Demo/DemoJ_Report.cs b/Src/Asp.Net/AccessTest/Demo/DemoJ_Report.cs new file mode 100644 index 000000000..2089b0545 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoJ_Report.cs @@ -0,0 +1,142 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoJ_Report + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### DemoJ_Report Start ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + Demo1(db); + Demo2(db); + Demo3(db); + } + + private static void Demo1(SqlSugarClient db) + { + var list = new List() { 1, 2, 3,1,2 }; + var query1 = db.Queryable(); + var queryable2 = db.Reportable(list).ToQueryable(); + var x = db.Queryable(query1, queryable2, (x1, x2) => x1.Id.Equals(x2.ColumnName)) + .Select((x1, x2) => new { x = x1.Id, x2 = x2.ColumnName }).ToList(); + } + private static void Demo2(SqlSugarClient db) + { + var list = db.Queryable().ToList(); + var query1 = db.Queryable(); + var queryable2 = db.Reportable(list).ToQueryable(); + var x = db.Queryable(query1, queryable2, (x1, x2) => x1.Id.Equals(x2.OrderId)) + .Select((x1, x2) => new { name = x1.Name,id=x1.Id, orderid = x2.OrderId }).ToList(); + } + private static void Demo3(SqlSugarClient db) + { + db.CodeFirst.InitTables(); + db.Deleteable().ExecuteCommand(); + db.Insertable(new operateinfo() + { + id=1, + operate_type=1, + operate_time=Convert.ToDateTime("2021-1-1") + }).ExecuteCommand(); + db.Insertable(new operateinfo() + { + id = 1, + operate_type = 1, + operate_time = Convert.ToDateTime("2021-1-2") + }).ExecuteCommand(); + db.Insertable(new operateinfo() + { + id = 1, + operate_type = 1, + operate_time = Convert.ToDateTime("2021-3-1") + }).ExecuteCommand(); + db.Insertable(new operateinfo() + { + id = 1, + operate_type = 1, + operate_time = Convert.ToDateTime("2021-3-2") + }).ExecuteCommand(); + db.Insertable(new operateinfo() + { + id = 1, + operate_type = 1, + operate_time = Convert.ToDateTime("2021-4-2") + }).ExecuteCommand(); + + + var queryableLeft = db.Reportable(ReportableDateType.MonthsInLast1years).ToQueryable(); + var queryableRight = db.Queryable(); + var list= db.Queryable(queryableLeft, queryableRight, JoinType.Left, + (x1, x2) => x2.operate_time.ToString("yyyy-MM")== x1.ColumnName .ToString("yyyy-MM")) + .GroupBy((x1,x2)=>x1.ColumnName) + .Where(x1=>SqlFunc.Between(x1.ColumnName,"2021-01-01",DateTime.Now)) + .Select((x1, x2) => new + { + count=SqlFunc.AggregateSum(SqlFunc.IIF(x2.id>0,1,0)) , + date=x1.ColumnName.ToString("yyyy-MM") + + }).ToList(); + } + + + public partial class operateinfo + { + public operateinfo() + { + + + } + /// + /// Desc:操作序号 + /// Default: + /// Nullable:False + /// + public int id { get; set; } + + /// + /// Desc:操作时间 + /// Default: + /// Nullable:False + /// + public DateTime operate_time { get; set; } + + /// + /// Desc:操作类型 + /// Default: + /// Nullable:False + /// + public int operate_type { get; set; } + + /// + /// Desc:操作人编号 + /// Default: + /// Nullable:False + /// + public int user_id { get; set; } + + } + } + +} \ No newline at end of file diff --git a/Src/Asp.Net/AccessTest/Demo/DemoL_Snowflake.cs b/Src/Asp.Net/AccessTest/Demo/DemoL_Snowflake.cs new file mode 100644 index 000000000..7111083d9 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoL_Snowflake.cs @@ -0,0 +1,49 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoL_Snowflake + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### DemoL_Snowflake ####"); + + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true, + AopEvents = new AopEvents + { + OnLogExecuting = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + } + } + }); + db.CodeFirst.InitTables(); + Console.WriteLine(db.Queryable().Count()); + var id= db.Insertable(new SnowflakeModel() + { + Name="哈哈" + }).ExecuteReturnSnowflakeId(); + var ids = db.Insertable(db.Queryable().Take(10).ToList()).ExecuteReturnSnowflakeIdList(); + Console.WriteLine(db.Queryable().Count()); + } + } + public class SnowflakeModel + { + [SugarColumn(IsPrimaryKey =true)] + public long Id { get; set; } + + public string Name{get;set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoM_UnitOfWork.cs b/Src/Asp.Net/AccessTest/Demo/DemoM_UnitOfWork.cs new file mode 100644 index 000000000..2c8006cc1 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoM_UnitOfWork.cs @@ -0,0 +1,72 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoM_UnitOfWork + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### DemoM_UnitOfWork ####"); + + + DbContext.Db.UseTran(() => + { + + var id = DbContext.CustomDal.InsertReturnIdentity(new Custom() { Id = 1, Name = "guid" }); + var id2 = DbContext.OrderDal.InsertReturnIdentity(new Order() { Name = "guid2", Price = 0, CreateTime = DateTime.Now, CustomId = 1 }); + throw new Exception(""); + }, + e => + { + //throw e; + }); + Console.WriteLine(""); + Console.WriteLine("#### Saveable End ####"); + } + public class DbContext + { + public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig() + { + DbType = SqlSugar.DbType.SqlServer, + ConnectionString = Config.ConnectionString, + IsAutoCloseConnection = true + }, db => { + //单例参数配置,所有上下文生效 + db.Aop.OnLogExecuting = (s, p) => + { + Console.WriteLine(s); + }; + }); + + public static DbSet OrderDal => new DbSet(); + public static DbSet CustomDal => new DbSet(); + + + public class DbSet : SimpleClient where T : class, new() + { + public DbSet(ISqlSugarClient context = null) : base(context)//需要有构造参数 + { + base.Context = DbContext.Db; + } + + /// + /// 扩展方法,自带方法不能满足的时候可以添加新方法 + /// + /// + public List CommQuery(string json) + { + //base.Context.Queryable().ToList();可以拿到SqlSugarClient 做复杂操作 + return null; + } + + } + } + + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/DemoN_SplitTable.cs b/Src/Asp.Net/AccessTest/Demo/DemoN_SplitTable.cs new file mode 100644 index 000000000..05d9c356c --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/DemoN_SplitTable.cs @@ -0,0 +1,100 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DemoN_SplitTable + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### CodeFirst Start ####"); + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() + { + DbType = DbType.SqlServer, + ConnectionString = Config.ConnectionString, + InitKeyType = InitKeyType.Attribute, + IsAutoCloseConnection = true + }); + db.Aop.OnLogExecuted = (s, p) => + { + Console.WriteLine(s); + Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); + }; + + //初始化分表 + db.CodeFirst.SplitTables().InitTables(); + + Console.WriteLine(); + + //根据最近3个表进行查询 + var list=db.Queryable() + .SplitTable(DateTime.Now.Date.AddYears(-1),DateTime.Now) + .ToList(); + + Console.WriteLine(); + + //根据时间选出的表进行查询 + var list2 = db.Queryable().SplitTable(tabs => tabs.Where(it=> it.Date>=DateTime.Now.AddYears(-2))).ToList(); + + Console.WriteLine(); + + //删除数据只在最近3张表执行操作 + var x = db.Deleteable().Where(it=>it.Pk==Guid.NewGuid()).SplitTable(tabs => tabs.Take(3)).ExecuteCommand(); + + Console.WriteLine(); + + var tableName = db.SplitHelper().GetTableName(DateTime.Now.AddDays(-111)); + + var listNull= db.Queryable().SplitTable(ta => ta.InTableNames(tableName)).ToList(); + + var tableName2 = db.SplitHelper(new OrderSpliteTest() { Time=DateTime.Now}).GetTableNames(); + var tableName3 = db.SplitHelper(new List { + new OrderSpliteTest() { Time = DateTime.Now }, + new OrderSpliteTest() { Time = DateTime.Now }, + new OrderSpliteTest() { Time = DateTime.Now.AddMonths(-10) } + }).GetTableNames(); + var x2 = db.Updateable() + .SetColumns(it=>it.Name=="a") + .Where(it => it.Pk == Guid.NewGuid()) + .SplitTable(tabs => tabs.InTableNames(tableName2)) + .ExecuteCommand(); + + Console.WriteLine(); + + //按日分表 + var x3 = db.Insertable(new OrderSpliteTest() { Name="A" }).SplitTable().ExecuteCommand(); + + Console.WriteLine(); + ////强制分表类型 + var x4 = db.Insertable(new OrderSpliteTest() { Name = "A" ,Time=DateTime.Now.AddDays(-1) }).SplitTable().ExecuteCommand(); + + //分表支持BulkCopy + db.Fastest().SplitTable().BulkCopy(new List { + new OrderSpliteTest() { Pk=Guid.NewGuid(),Name ="a", Time = DateTime.Now }, + new OrderSpliteTest() {Pk=Guid.NewGuid(),Name ="a", Time = DateTime.Now }, + new OrderSpliteTest() {Pk=Guid.NewGuid(),Name ="a", Time = DateTime.Now.AddMonths(-10) } + }); + + db.Fastest().SplitTable().BulkUpdate(db.Queryable().SplitTable(it=>it).ToList()); + db.Fastest().SplitTable().BulkUpdate(db.Queryable().SplitTable(it => it).ToList(),new string[] { "pk"},new string[] { "name"}); + Console.WriteLine("#### CodeFirst end ####"); + } + + [SplitTable(SplitType.Day)] + [SqlSugar.SugarTable("Taxxx0101_{year}{month}{day}")] + public class OrderSpliteTest + { + [SugarColumn(IsPrimaryKey =true)] + public Guid Pk{ get; set; } + public string Name { get; set; } + [SugarColumn(IsNullable =true)] + [SplitField] + public DateTime Time { get; set; } + } + } +} diff --git a/Src/Asp.Net/AccessTest/Demo/Democ_GobalFilter.cs b/Src/Asp.Net/AccessTest/Demo/Democ_GobalFilter.cs new file mode 100644 index 000000000..b66ae23f0 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Demo/Democ_GobalFilter.cs @@ -0,0 +1,108 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + public class DemoC_GobalFilter + { + public static void Init() + { + Console.WriteLine(""); + Console.WriteLine("#### Filter Start ####"); + + TableFilterDemo(); + + NameFilterDemo(); + + Console.WriteLine("#### Filter End ####"); + } + private static void TableFilterDemo() + { + var db = GetInstance(); + //Order add filter + db.QueryFilter.Add(new TableFilterItem(it => it.Name.Contains("a"),true)); + + db.Queryable().ToList(); + + db.Queryable().ToList(); + //SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order] WHERE ([Name] like '%'+@MethodConst0+'%') + + //delete Filter + db.Deleteable().EnableQueryFilter().Where(it=>it.Id==1).ExecuteCommand(); + + db.Queryable((i, o) => i.OrderId == o.Id) + .Where(i => i.OrderId != 0) + .Select("i.*").ToList(); + //SELECT i.* FROM [OrderDetail] i ,[Order] o WHERE ( [i].[OrderId] = [o].[Id] ) AND ( [i].[OrderId] <> @OrderId0 ) AND ([o].[Name] like '%'+@MethodConst1+'%') + + //no filter + db.Queryable().Filter(null, false).ToList(); + //SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order] + + db.Queryable().LeftJoin((x, y) => x.ItemId == y.Id).ToList(); + } + + + private static void NameFilterDemo() + { + var db2 = GetInstance(); + db2.QueryFilter.Add(new SqlFilterItem() + { + FilterName = "Myfilter1", + FilterValue = it => + { + //Writable logic + return new SqlFilterResult() { Sql = " name like '%a%' " }; + }, + IsJoinQuery = false // single query + }); + db2.QueryFilter.Add(new SqlFilterItem() + { + FilterName = "Myfilter1", + FilterValue = it => + { + //Writable logic + return new SqlFilterResult() { Sql = " o.name like '%a%' " }; + }, + IsJoinQuery = true //join query + }); + + db2.Queryable() + .Where(it => it.Name == "jack") + .Filter("Myfilter1") + //IF .Filter("Myfilter",false) only execute Myfilter + .ToList(); + //SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order] + //WHERE ( [Name] = 'jack' ) AND name like '%a%' + + + db2.Queryable((o, i) => o.Id == i.OrderId) + .Where(o => o.Name == "jack") + .Filter("Myfilter1") + .Select(o => o) + .ToList(); + //SELECT o.* FROM[Order] o, [OrderDetail] i WHERE ( [o].[Id] = [i].[OrderId]) + //AND([o].[Name] = 'jack') AND o.name like '%a%' + + //no filter + db2.Queryable().Filter(null, false).ToList(); + //SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order] + } + + + public static SqlSugarClient GetInstance() + { + SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.SqlServer, ConnectionString = Config.ConnectionString, IsAutoCloseConnection = true }); + db.Aop.OnLogExecuted = (sql, p) => + { + Console.WriteLine(sql); + Console.WriteLine(string.Join(",",p.Select(it=>it.ParameterName+":"+it.Value))); + Console.WriteLine(); + }; + return db; + } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/AttributeTable.cs b/Src/Asp.Net/AccessTest/Models/AttributeTable.cs new file mode 100644 index 000000000..fa153072f --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/AttributeTable.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + [Table( "MyAttributeTable")] + //[SugarTable("CustomAttributeTable")] + public class AttributeTable + { + + [Key] + //[SugarColumn(IsPrimaryKey =true)] + public string Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/Custom.cs b/Src/Asp.Net/AccessTest/Models/Custom.cs new file mode 100644 index 000000000..3b8871c57 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/Custom.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Custom + { + public int Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/DataDictionary.cs b/Src/Asp.Net/AccessTest/Models/DataDictionary.cs new file mode 100644 index 000000000..5b0b31b39 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/DataDictionary.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class DataDictionary + { + public string Code { get; set; } + public string Name { get; set; } + public string Type { get; set; } + } + + public class Person + { + //数据库字段 + [SqlSugar.SugarColumn(IsPrimaryKey =true,IsIdentity =true)] + public int Id { get; set; } + public string Name { get; set; } + public int SexId { get; set; } + public int CityId { get; set; } + public int ProviceId { get; set; } + + //非数据库字段 + [SqlSugar.SugarColumn(IsIgnore =true)] + public string SexName { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public string CityName { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public string ProviceName { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/EntityMapper.cs b/Src/Asp.Net/AccessTest/Models/EntityMapper.cs new file mode 100644 index 000000000..b597012fb --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/EntityMapper.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SqlSugar; +namespace OrmTest +{ + [SugarTable("MyEntityMapper")] + public class EntityMapper + { + [SugarColumn(ColumnName ="MyName")] + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/Mapper.cs b/Src/Asp.Net/AccessTest/Models/Mapper.cs new file mode 100644 index 000000000..bbf4e9af4 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/Mapper.cs @@ -0,0 +1,56 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + [SugarTable("OrderDetail")] + public class OrderItemInfo + { + [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int ItemId { get; set; } + public int OrderId { get; set; } + public decimal? Price { get; set; } + [SqlSugar.SugarColumn(IsNullable = true)] + public DateTime? CreateTime { get; set; } + [SugarColumn(IsIgnore = true)] + public Order Order { get; set; } + } + [SugarTable("Order")] + public class OrderInfo + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + [SugarColumn(IsIgnore = true)] + public List Items { get; set; } + } + public class ABMapping + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int AId { get; set; } + public int BId { get; set; } + [SugarColumn(IsIgnore = true)] + public A A { get; set; } + [SugarColumn(IsIgnore = true)] + public B B { get; set; } + + } + public class A + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + [SugarColumn(IsIgnore = true)] + public List BList { get; set; } + } + public class B + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/Order.cs b/Src/Asp.Net/AccessTest/Models/Order.cs new file mode 100644 index 000000000..d7ff068b8 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/Order.cs @@ -0,0 +1,24 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + + public class Order + { + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + + public string Name { get; set; } + public decimal Price { get; set; } + [SugarColumn(IsNullable = true)] + public DateTime CreateTime { get; set; } + [SugarColumn(IsNullable =true)] + public int CustomId { get; set; } + [SugarColumn(IsIgnore = true)] + public List Items { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/OrderItem.cs b/Src/Asp.Net/AccessTest/Models/OrderItem.cs new file mode 100644 index 000000000..fb7d0a7d9 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/OrderItem.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OrmTest +{ + [SqlSugar.SugarTable("OrderDetail")] + public class OrderItem + { + [SqlSugar.SugarColumn(IsPrimaryKey =true, IsIdentity =true)] + public int ItemId { get; set; } + public int OrderId { get; set; } + public decimal? Price { get; set; } + [SqlSugar.SugarColumn(IsNullable = true)] + public DateTime? CreateTime { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public string OrderName { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/SubInsertTest.cs b/Src/Asp.Net/AccessTest/Models/SubInsertTest.cs new file mode 100644 index 000000000..702f93a93 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/SubInsertTest.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class RootTable0 + { + [SqlSugar.SugarColumn(IsPrimaryKey =true,IsIdentity =true)] + public int Id { get; set; } + public string Name { get; set; } + [SqlSugar.SugarColumn(IsIgnore =true)] + public TwoItem TwoItem { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public TwoItem2 TwoItem2 { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public List TwoItem3 { get; set; } + } + public class TwoItem + { + [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + public int Id { get; set; } + public int RootId { get; set; } + public string Name { get; set; } + } + public class TwoItem2 + { + [SqlSugar.SugarColumn(IsPrimaryKey = true)] + public string Id { get; set; } + public int RootId { get; set; } + [SqlSugar.SugarColumn(IsIgnore =true)] + public List ThreeItem2 { get; set; } + } + public class TwoItem3 + { + [SqlSugar.SugarColumn(IsPrimaryKey = true)] + public int Id { get; set; } + public string Name { get; set; } + public string Desc { get; set; } + } + public class ThreeItem2 + { + [SqlSugar.SugarColumn(IsPrimaryKey = true)] + + public int Id { get; set; } + public string Name { get; set; } + public string TwoItem2Id { get; set; } + } + + public class Country + { + [SqlSugar.SugarColumn(IsPrimaryKey = true)] + public int Id { get; set; } + public string Name { get; set; } + + [SqlSugar.SugarColumn(IsIgnore = true)] + public List Provinces { get; set; } + } + + public class Province + { + [SqlSugar.SugarColumn(IsPrimaryKey =true)] + public int Id { get; set; } + public string Name { get; set; } + public int CountryId { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public List citys { get; set; } + } + + public class City + { + [SqlSugar.SugarColumn(IsPrimaryKey = true)] + public int Id { get; set; } + public int ProvinceId { get; set; } + public string Name { get; set; } + } + + + public class Country1 + { + [SqlSugar.SugarColumn(IsPrimaryKey = true,IsIdentity =true)] + public int Id { get; set; } + public string Name { get; set; } + + [SqlSugar.SugarColumn(IsIgnore = true)] + public List Provinces { get; set; } + } + + public class Province1 + { + [SqlSugar.SugarColumn(IsPrimaryKey = true,IsIdentity =true)] + public int Id { get; set; } + public string Name { get; set; } + public int CountryId { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public List citys { get; set; } + } + + public class City1 + { + [SqlSugar.SugarColumn(IsPrimaryKey = true,IsIdentity =true)] + public int Id { get; set; } + public int ProvinceId { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/TestTree.cs b/Src/Asp.Net/AccessTest/Models/TestTree.cs new file mode 100644 index 000000000..b8250828a --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/TestTree.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class TestTree + { + [SqlSugar.SugarColumn(ColumnDataType = "hierarchyid")] + public string TreeId { get; set; } + [SqlSugar.SugarColumn(ColumnDataType = "Geography")] + public string GId { get; set; } + public string Name { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/Tree.cs b/Src/Asp.Net/AccessTest/Models/Tree.cs new file mode 100644 index 000000000..d2878de64 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/Tree.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class Tree + { + [SqlSugar.SugarColumn(IsPrimaryKey =true)] + public int Id { get; set; } + public string Name { get; set; } + public int ParentId { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public Tree Parent { get; set; } + [SqlSugar.SugarColumn(IsIgnore = true)] + public List Child { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Models/ViewOrder.cs b/Src/Asp.Net/AccessTest/Models/ViewOrder.cs new file mode 100644 index 000000000..fcd465747 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Models/ViewOrder.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OrmTest +{ + public class ViewOrder:Order + { + public string CustomName { get; set; } + } +} diff --git a/Src/Asp.Net/AccessTest/Program.cs b/Src/Asp.Net/AccessTest/Program.cs new file mode 100644 index 000000000..15b4b3dee --- /dev/null +++ b/Src/Asp.Net/AccessTest/Program.cs @@ -0,0 +1,46 @@ +using System; + +namespace OrmTest +{ + class Program + { + /// + /// Set up config.cs file and start directly F5 + /// 设置Config.cs文件直接F5启动例子 + /// + /// + static void Main(string[] args) + { + + //Demo + Demo0_SqlSugarClient.Init(); + Demo1_Queryable.Init(); + Demo2_Updateable.Init(); + Demo3_Insertable.Init(); + Demo4_Deleteable.Init(); + Demo5_SqlQueryable.Init(); + DemoN_SplitTable.Init(); + Demo6_Queue.Init(); + Demo7_Ado.Init(); + Demo8_Saveable.Init(); + Demo9_EntityMain.Init(); + DemoA_DbMain.Init(); + DemoB_Aop.Init(); + DemoC_GobalFilter.Init(); + DemoD_DbFirst.Init();; + DemoE_CodeFirst.Init(); + DemoF_Utilities.Init(); + DemoG_SimpleClient.Init(); + DemoH_Tenant.Init(); + DemoJ_Report.Init(); + DemoL_Snowflake.Init(); + DemoM_UnitOfWork.Init(); + ; + + Console.WriteLine("all successfully."); + Console.ReadKey(); + } + + + } +} diff --git a/Src/Asp.Net/AccessTest/Properties/AssemblyInfo.cs b/Src/Asp.Net/AccessTest/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..e2a517946 --- /dev/null +++ b/Src/Asp.Net/AccessTest/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("AccessTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AccessTest")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("fa1b8c67-44c2-4937-96a2-7e01b9f5941e")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [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 ba8cab588..b93af6a45 100644 --- a/Src/Asp.Net/SqlSugar.sln +++ b/Src/Asp.Net/SqlSugar.sln @@ -37,6 +37,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySqlConnectorTest", "MySql EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SqlSugar.CustomDatabase", "SqlSugar.CustomDatabase", "{BD138454-2F77-4085-81EF-66E7F9EBE3DA}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AccessTest", "AccessTest\AccessTest.csproj", "{FA1B8C67-44C2-4937-96A2-7E01B9F5941E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -103,6 +105,10 @@ Global {7F705C44-F878-4706-AB9B-8D35030A8222}.Debug|Any CPU.Build.0 = Debug|Any CPU {7F705C44-F878-4706-AB9B-8D35030A8222}.Release|Any CPU.ActiveCfg = Release|Any CPU {7F705C44-F878-4706-AB9B-8D35030A8222}.Release|Any CPU.Build.0 = Release|Any CPU + {FA1B8C67-44C2-4937-96A2-7E01B9F5941E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA1B8C67-44C2-4937-96A2-7E01B9F5941E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA1B8C67-44C2-4937-96A2-7E01B9F5941E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA1B8C67-44C2-4937-96A2-7E01B9F5941E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE