mirror of
https://gitee.com/dotnetchina/SqlSugar.git
synced 2025-09-18 17:48:11 +08:00
Add AccessTest
This commit is contained in:
100
Src/Asp.Net/AccessTest/AccessTest.csproj
Normal file
100
Src/Asp.Net/AccessTest/AccessTest.csproj
Normal file
@@ -0,0 +1,100 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{FA1B8C67-44C2-4937-96A2-7E01B9F5941E}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<RootNamespace>AccessTest</RootNamespace>
|
||||
<AssemblyName>AccessTest</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.ComponentModel.DataAnnotations" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Config.cs" />
|
||||
<Compile Include="Demo\Demo0_SqlSugarClient.cs" />
|
||||
<Compile Include="Demo\Demo1_Queryable.cs" />
|
||||
<Compile Include="Demo\Demo2_Updateable.cs" />
|
||||
<Compile Include="Demo\Demo3_Insertable.cs" />
|
||||
<Compile Include="Demo\Demo4_Deleteable.cs" />
|
||||
<Compile Include="Demo\Demo5_SqlQueryable.cs" />
|
||||
<Compile Include="Demo\Demo6_Queue.cs" />
|
||||
<Compile Include="Demo\Demo7_Ado.cs" />
|
||||
<Compile Include="Demo\Demo8_Saveable.cs" />
|
||||
<Compile Include="Demo\Demo9_EntityMain.cs" />
|
||||
<Compile Include="Demo\DemoA_DbMain.cs" />
|
||||
<Compile Include="Demo\DemoB_Aop.cs" />
|
||||
<Compile Include="Demo\Democ_GobalFilter.cs" />
|
||||
<Compile Include="Demo\DemoD_DbFirst.cs" />
|
||||
<Compile Include="Demo\DemoE_CodeFirst.cs" />
|
||||
<Compile Include="Demo\DemoF_Utilities.cs" />
|
||||
<Compile Include="Demo\DemoG_SimpleClient.cs" />
|
||||
<Compile Include="Demo\DemoH_Tenant.cs" />
|
||||
<Compile Include="Demo\DemoJ_Report.cs" />
|
||||
<Compile Include="Demo\DemoL_Snowflake.cs" />
|
||||
<Compile Include="Demo\DemoM_UnitOfWork.cs" />
|
||||
<Compile Include="Demo\DemoN_SplitTable.cs" />
|
||||
<Compile Include="Models\AttributeTable.cs" />
|
||||
<Compile Include="Models\Custom.cs" />
|
||||
<Compile Include="Models\DataDictionary.cs" />
|
||||
<Compile Include="Models\EntityMapper.cs" />
|
||||
<Compile Include="Models\Mapper.cs" />
|
||||
<Compile Include="Models\Order.cs" />
|
||||
<Compile Include="Models\OrderItem.cs" />
|
||||
<Compile Include="Models\SubInsertTest.cs" />
|
||||
<Compile Include="Models\TestTree.cs" />
|
||||
<Compile Include="Models\Tree.cs" />
|
||||
<Compile Include="Models\ViewOrder.cs" />
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config">
|
||||
<SubType>Designer</SubType>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SqlSugar.Access\SqlSugar.Access.csproj">
|
||||
<Project>{0a27f276-d442-4e0a-b810-32d6074f0155}</Project>
|
||||
<Name>SqlSugar.Access</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj">
|
||||
<Project>{489bb790-226c-4fad-8d1e-51d72a7ff8e5}</Project>
|
||||
<Name>SqlSugar</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
3
Src/Asp.Net/AccessTest/App.config
Normal file
3
Src/Asp.Net/AccessTest/App.config
Normal file
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/></startup></configuration>
|
31
Src/Asp.Net/AccessTest/Config.cs
Normal file
31
Src/Asp.Net/AccessTest/Config.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
/// <summary>
|
||||
/// Setting up the database name does not require you to create the database
|
||||
/// 只需要设置IP和账户密码 ,自动建库
|
||||
/// </summary>
|
||||
public class Config
|
||||
{
|
||||
/// <summary>
|
||||
/// Account have permission to create database
|
||||
/// 用有建库权限的数据库账号
|
||||
/// </summary>
|
||||
public static string ConnectionString = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST";
|
||||
/// <summary>
|
||||
/// Account have permission to create database
|
||||
/// 用有建库权限的数据库账号
|
||||
/// </summary>
|
||||
public static string ConnectionString2 = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST2";
|
||||
/// <summary>
|
||||
/// Account have permission to create database
|
||||
/// 用有建库权限的数据库账号
|
||||
/// </summary>
|
||||
public static string ConnectionString3 = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST3";
|
||||
}
|
||||
}
|
450
Src/Asp.Net/AccessTest/Demo/Demo0_SqlSugarClient.cs
Normal file
450
Src/Asp.Net/AccessTest/Demo/Demo0_SqlSugarClient.cs
Normal file
@@ -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<SlaveConnectionConfig>() {
|
||||
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<Order>().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<Order, OrderItem,Custom>();//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<IConditionalModel> conModels = new List<IConditionalModel>();
|
||||
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<AttributeTable>();//Create Table
|
||||
|
||||
db.Insertable(new AttributeTable() { Id = Guid.NewGuid().ToString(), Name = "Name" }).ExecuteCommand();
|
||||
var list = db.Queryable<AttributeTable>().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<ConnectionConfig>()
|
||||
{
|
||||
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<Order>().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<Order>().Count());
|
||||
|
||||
// Example 1
|
||||
Console.WriteLine("Example 1");
|
||||
try
|
||||
{
|
||||
db.BeginTran();
|
||||
|
||||
db.ChangeDatabase("1");//use db1
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().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<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Example 2
|
||||
Console.WriteLine("Example 2");
|
||||
|
||||
var result = db.UseTran(() =>
|
||||
{
|
||||
|
||||
db.ChangeDatabase("1");//use db1
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().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<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
}
|
||||
|
||||
// Example 3
|
||||
Console.WriteLine("Example 3");
|
||||
Task<DbResult<bool>> 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<Order>().Count());
|
||||
Console.WriteLine(sqlServerdb.Queryable<Order>().Count());
|
||||
try
|
||||
{
|
||||
db.BeginTran();
|
||||
|
||||
sqlServerdb.Deleteable<Order>().ExecuteCommand();
|
||||
mysqldb.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine(mysqldb.Queryable<Order>().Count());
|
||||
Console.WriteLine(sqlServerdb.Queryable<Order>().Count());
|
||||
|
||||
throw new Exception("");
|
||||
db.CommitTran();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
db.RollbackTran();//数据回滚
|
||||
Console.WriteLine(mysqldb.Queryable<Order>().Count());
|
||||
Console.WriteLine(sqlServerdb.Queryable<Order>().Count());
|
||||
}
|
||||
Console.WriteLine("#### Distributed TransactionExample End ####");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///Async tran demo
|
||||
/// </summary>
|
||||
/// <param name="db"></param>
|
||||
/// <returns></returns>
|
||||
private static async Task<DbResult<bool>> AsyncTranDemo(SqlSugarClient db)
|
||||
{
|
||||
//need await all
|
||||
var result2 =await db.UseTranAsync(async () =>
|
||||
{
|
||||
//need await all
|
||||
|
||||
db.ChangeDatabase("1");//use db1
|
||||
await db.Deleteable<Order>().ExecuteCommandAsync();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
await db.Deleteable<Order>().ExecuteCommandAsync();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
throw new Exception("");
|
||||
|
||||
});
|
||||
Console.WriteLine("---Roll back");
|
||||
db.ChangeDatabase("1");//use sqlserver
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use mysql
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
return result2;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DbContext Example 1
|
||||
/// </summary>
|
||||
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<Order> OrderDb => new SimpleClient<Order>(Db);
|
||||
public SimpleClient<OrderItem> OrderItemDb => new SimpleClient<OrderItem>(Db);
|
||||
}
|
||||
|
||||
|
||||
public class OrderDal : DbContext<Order>
|
||||
{
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// DbContext Example 2
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class DbContext<T> 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<T> CurrentDb => new SimpleClient<T>(Db);
|
||||
public virtual T GetById(int id)
|
||||
{
|
||||
return CurrentDb.GetById(id);
|
||||
}
|
||||
public virtual List<T> GetList()
|
||||
{
|
||||
return CurrentDb.GetList();
|
||||
}
|
||||
public virtual bool Delete(int id)
|
||||
{
|
||||
return CurrentDb.DeleteById(id);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
571
Src/Asp.Net/AccessTest/Demo/Demo1_Queryable.cs
Normal file
571
Src/Asp.Net/AccessTest/Demo/Demo1_Queryable.cs
Normal file
@@ -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<DataDictionary> datas = new List<DataDictionary>();
|
||||
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<DataDictionary>();
|
||||
db.CodeFirst.InitTables<Person>();
|
||||
db.DbMaintenance.TruncateTable<DataDictionary>();
|
||||
db.Insertable(datas).ExecuteCommand();
|
||||
|
||||
if (!db.ConfigQuery.Any())
|
||||
{
|
||||
var types= db.Queryable<DataDictionary>().Select(it => it.Type).Distinct().ToList();
|
||||
foreach (var type in types)
|
||||
{
|
||||
db.ConfigQuery.SetTable<DataDictionary>(it => it.Code, it => it.Name, type, it => it.Type == type);
|
||||
}
|
||||
|
||||
db.ConfigQuery.SetTable<Order>(it => it.Id, it => it.Name, "01", it => it.Id > 1);
|
||||
db.ConfigQuery.SetTable<Order>(it => it.Id, it => it.Name, "02", it => it.Id > 2);
|
||||
db.ConfigQuery.SetTable<Order>(it => it.Id, it => it.Name, null);
|
||||
}
|
||||
|
||||
|
||||
var res=db.Queryable<Person>().Select(it => new Person()
|
||||
{
|
||||
Id=it.Id.SelectAll(),
|
||||
SexName=it.SexId.GetConfigValue<DataDictionary>("sex"),
|
||||
ProviceName = it.SexId.GetConfigValue<DataDictionary>("province"),
|
||||
CityName = it.SexId.GetConfigValue<DataDictionary>("city"),
|
||||
}).ToList();//也支持支持写在Where或者Orderby
|
||||
|
||||
var list = db.Queryable<OrderItem>().Select(it => new OrderItem
|
||||
{
|
||||
ItemId = it.ItemId.SelectAll(),
|
||||
OrderName = it.OrderId.GetConfigValue<Order>("01")
|
||||
}).ToList();
|
||||
var list2 = db.Queryable<OrderItem>().Select(it => new OrderItem
|
||||
{
|
||||
ItemId = it.ItemId.SelectAll(),
|
||||
OrderName = it.OrderId.GetConfigValue<Order>("02")
|
||||
}).ToList();
|
||||
var list3 = db.Queryable<OrderItem>().Select(it => new OrderItem
|
||||
{
|
||||
ItemId = it.ItemId.SelectAll(),
|
||||
OrderName = it.OrderId.GetConfigValue<Order>()
|
||||
}).ToList();
|
||||
|
||||
var list4 = db.Queryable<OrderItem>().Select(it => new OrderItem
|
||||
{
|
||||
ItemId = it.ItemId.SelectAll(),
|
||||
OrderName = it.OrderId.GetConfigValue<Order>()
|
||||
})
|
||||
.Where(it=>it.OrderId.GetConfigValue<Order>()== "order1")
|
||||
.OrderBy(it=>it.OrderId.GetConfigValue<Order>()).ToList();
|
||||
|
||||
var list5 = db.Queryable<Order, OrderItem>((o, i) => o.Id == i.OrderId)
|
||||
.OrderBy((o,i)=>i.OrderId.GetConfigValue<Order>(),OrderByType.Desc)
|
||||
.Select<ViewOrder>((o,i)=>new ViewOrder() {
|
||||
Id= o.Id.SelectAll(),
|
||||
Name=i.OrderId.GetConfigValue<Order>()
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static void EasyExamples()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Examples Start ####");
|
||||
var db = GetInstance();
|
||||
var dbTime = db.GetDate();
|
||||
var getAll = db.Queryable<Order>().Where(it=> SqlFunc.EqualsNull(it.Name,null)).ToList();
|
||||
var getOrderBy = db.Queryable<Order>().OrderBy(it => it.Name,OrderByType.Desc).ToList();
|
||||
var getOrderBy2 = db.Queryable<Order>().OrderBy(it => it.Id).OrderBy(it => it.Name, OrderByType.Desc).ToList();
|
||||
var getOrderBy3 = db.Queryable<Order>().OrderBy(it =>new { it.Name,it.Id}).ToList();
|
||||
var getRandom = db.Queryable<Order>().OrderBy(it => SqlFunc.GetRandom()).First();
|
||||
var getByPrimaryKey = db.Queryable<Order>().InSingle(2);
|
||||
var getSingleOrDefault = db.Queryable<Order>().Where(it => it.Id == 1).Single();
|
||||
var getFirstOrDefault = db.Queryable<Order>().First();
|
||||
var getByWhere = db.Queryable<Order>().Where(it => it.Id == 1 || it.Name == "a").ToList();
|
||||
var getByWhere2 = db.Queryable<Order>().Where(it => it.Id == DateTime.Now.Year).ToList();
|
||||
var getByFuns = db.Queryable<Order>().Where(it => SqlFunc.IsNullOrEmpty(it.Name)).ToList();
|
||||
var getByFuns2 = db.Queryable<Order>().GroupBy(it => it.Name).Select(it => SqlFunc.AggregateDistinctCount(it.Price)).ToList();
|
||||
var getDicionary = db.Queryable<Order>().ToDictionary(it => it.Id, it => it.Name);
|
||||
var getDicionaryList = db.Queryable<Order>().ToDictionaryList();
|
||||
var getTest = db.Queryable<Order>().Where(it =>string.IsNullOrWhiteSpace( it.Name)).ToList();
|
||||
var test01 = db.Queryable<Order>().PartitionBy(it => it.Id).ToList();
|
||||
var q1 = db.Queryable<Order>().Take(1);
|
||||
var q2 = db.Queryable<Order>().Take(2);
|
||||
var test02 = db.Union(q1, q2).ToList();
|
||||
var test03 = db.Queryable<Order>().Take(1).ToList();
|
||||
var dp = DateTime.Now;
|
||||
var test05 = db.Queryable<Order>().Where(it => it.CreateTime.Month== dp.Month).ToList();
|
||||
var test06 = db.Queryable<Order>()
|
||||
.ToPivotTable(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));
|
||||
|
||||
var test07 = db.Queryable<Order>()
|
||||
.ToPivotList(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));
|
||||
|
||||
var test08 = db.Queryable<Order>()
|
||||
.ToPivotJson(it => it.Id, it => it.Name, it => it.Sum(x => x.Price));
|
||||
|
||||
var test09 = db.Queryable<Order>().PartitionBy(it=>it.Id).ToPageListAsync(1,2,0);
|
||||
test09.Wait();
|
||||
|
||||
int c = 0;
|
||||
var test10 = db.Queryable<Order>().ToPageList(1, 2, ref c);
|
||||
var test11 = db.Queryable<Order>().GroupBy(it=>new { it.CreateTime.Year }).Select(it=>it.CreateTime.Year).ToList();
|
||||
var test12 = db.Queryable<Order>().GroupBy(it => it.CreateTime.Date ).Select(it => it.CreateTime.Date).ToList();
|
||||
var test13 = db.Queryable<Order>().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<Order>()
|
||||
.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<Order, Order>((o, i) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Name == SqlFunc.ToString(SqlFunc.MergeString(",", i.Name, ","))
|
||||
))
|
||||
.Select<ViewOrder>().ToList();
|
||||
var test16 = db.Queryable<Order>().Select(it => SqlFunc.SqlServer_DateDiff("day", DateTime.Now.AddDays(-1), DateTime.Now)).ToList();
|
||||
var test17 =
|
||||
db.Queryable<Order>()
|
||||
.Select<Order>()
|
||||
.MergeTable()
|
||||
.Select(it => new ViewOrder()
|
||||
{
|
||||
Name = SqlFunc.Subqueryable<Order>().Select(s => s.Name)
|
||||
}).ToList(); ;
|
||||
var test18 = db.UnionAll(
|
||||
db.Queryable<Order>() ,
|
||||
db.Queryable<Order>()
|
||||
)
|
||||
.Select(it=>new ViewOrder(){
|
||||
Name=SqlFunc.Subqueryable<Order>().Select(s=>s.Name)
|
||||
}).ToList();
|
||||
var test19 = db.Queryable<Order>().Select<ViewOrder>().ToList();
|
||||
var test20 = db.Queryable<Order>().LeftJoin<Custom>((o, cs) =>o.Id==cs.Id)
|
||||
.ToDictionary(it => it.Id, it => it.Name);
|
||||
|
||||
var test21 = db.Queryable<Order>().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<Order> list = db.Queryable<Order>().ToList();
|
||||
|
||||
var x2=db.Ado.SqlQueryAsync<Order>("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<Order>().First(it => it.Id == 1);
|
||||
|
||||
DataTable dataTable = db.Queryable<Order>().Select(it => it.Id).ToDataTable();
|
||||
|
||||
var json = db.Queryable<Order>().ToJson();
|
||||
|
||||
List<int> listInt = db.Queryable<Order>().Select(it => it.Id).ToList();
|
||||
|
||||
var dynamic = db.Queryable<Order>().Select<dynamic>().ToList();
|
||||
|
||||
var viewModel = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId ,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select<ViewOrder>().ToList();
|
||||
|
||||
var newDynamic = db.Queryable<Order, OrderItem, Custom>((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<Order, OrderItem, Custom>((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<Order, OrderItem, Custom>((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<Order, OrderItem, Custom>((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<Dictionary<string, object>> ListDic = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select<ExpandoObject>().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<Order>().Take(10).Select(it => new
|
||||
{
|
||||
customName=SqlFunc.Subqueryable<Custom>().Where("it.CustomId=id").Select(s=>s.Name),
|
||||
customName2 = SqlFunc.Subqueryable<Custom>().Where("it.CustomId = id").Where(s => true).Select(s => s.Name)
|
||||
}).ToList();
|
||||
|
||||
var list1 = db.Queryable<Order>().Select(it => new
|
||||
{
|
||||
id = SqlFunc.Subqueryable<Custom>().Where(s => s.Id == 1).Sum(s => s.Id) * 1
|
||||
}).ToList();
|
||||
|
||||
var list2 = db.Queryable<Order>().Where(it =>
|
||||
SqlFunc.Subqueryable<OrderItem>()
|
||||
.LeftJoin<OrderItem>((i,z)=>i.ItemId==z.ItemId)
|
||||
.InnerJoin<OrderItem>((i,z,y) => i.ItemId == z.ItemId)
|
||||
.InnerJoin<OrderItem>((i,z,y,h) => i.ItemId == z.ItemId)
|
||||
.InnerJoin<OrderItem>((i, z, y, h, n) => i.ItemId == z.ItemId)
|
||||
.Where((i, z) => i.ItemId == z.ItemId)
|
||||
.Any()
|
||||
).ToList();
|
||||
|
||||
var list3 = db.Queryable<Order>().Select(it => new
|
||||
{
|
||||
customName = SqlFunc.Subqueryable<Custom>().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<Custom>().And(s => s.Id==1).ToExpression();
|
||||
var list4 = db.Queryable<Order>().Select(it => new
|
||||
{
|
||||
customName = SqlFunc.Subqueryable<Custom>().Where(exp).Where(exp).GroupBy(s => s.Name).Having(s => SqlFunc.AggregateCount(s.Id) > 0).Select(s => s.Name)
|
||||
}).ToList();
|
||||
|
||||
|
||||
var list5 = db.Queryable<Order>().Where(it =>
|
||||
SqlFunc.Subqueryable<OrderItem>()
|
||||
.LeftJoin<OrderItem>((i, y) => i.ItemId == y.ItemId)
|
||||
.InnerJoin<OrderItem>((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<Order>().Select(it => SqlFunc.CharIndex("a", "cccacc")).First();
|
||||
var list = db.Queryable<Order>().Select(it =>new ViewOrder()
|
||||
{
|
||||
|
||||
Id = SqlFunc.AggregateSum(SqlFunc.IF(it.Id > 0).Return(1).End(0))
|
||||
}).ToList();
|
||||
var list2 = db.Queryable<Order>().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<Tree>().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<Tree>()
|
||||
//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<Tree>().ToTree(it => it.Child, it => it.ParentId, 0);
|
||||
var allchilds= db.Queryable<Tree>().ToChildList(it => it.ParentId, 0);
|
||||
var allchilds1 = db.Queryable<Tree>().ToChildList(it => it.ParentId, 1);
|
||||
var allchilds2= db.Queryable<Tree>().ToChildList(it => it.ParentId, 2);
|
||||
var parentList = db.Queryable<Tree>().ToParentList(it => it.ParentId, 22);
|
||||
var parentList2 = db.Queryable<Tree>().ToParentList(it => it.ParentId, 222);
|
||||
var parentList3 = db.Queryable<Tree>().ToParentList(it => it.ParentId, 2);
|
||||
|
||||
//one to one
|
||||
var list2 = db.Queryable<OrderItemInfo>().Mapper(it => it.Order, it => it.OrderId).ToList();
|
||||
|
||||
//one to many
|
||||
var list3 = db.Queryable<Order>().Mapper(it => it.Items, it => it.Items.First().OrderId).ToList();
|
||||
|
||||
//many to many
|
||||
db.CodeFirst.InitTables<A, B, ABMapping>();
|
||||
|
||||
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<ABMapping>()
|
||||
.Mapper(it => it.A, it => it.AId)
|
||||
.Mapper(it => it.B, it => it.BId).ToList();
|
||||
|
||||
//Manual mode
|
||||
var result = db.Queryable<OrderInfo>().Take(10).Select<ViewOrder>().Mapper((itemModel, cache) =>
|
||||
{
|
||||
var allItems = cache.Get(orderList => {
|
||||
var allIds = orderList.Select(it => it.Id).ToList();
|
||||
return db.Queryable<OrderItem>().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<dynamic>().AS("order ").Where("id=id", new { id = 1 }).ToList();
|
||||
|
||||
var list2 = db.Queryable<dynamic>("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<Order, OrderItem, Custom>((o, i, c) => o.Id == i.OrderId&&c.Id == o.CustomId)
|
||||
.Select<ViewOrder>()
|
||||
.ToList();
|
||||
|
||||
//Join table
|
||||
var list2 = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, c.Id == o.CustomId
|
||||
))
|
||||
.Select<ViewOrder>().ToList();
|
||||
|
||||
//Join queryable
|
||||
var query1 = db.Queryable<Order, OrderItem>((o, i) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId
|
||||
))
|
||||
.Where(o => o.Name == "jack");
|
||||
|
||||
var query2 = db.Queryable<Custom>();
|
||||
var list3=db.Queryable(query1, query2,JoinType.Left, (p1, p2) => p1.CustomId == p2.Id).Select<ViewOrder>().ToList();
|
||||
|
||||
|
||||
var query3 = db.Union(
|
||||
db.Queryable<Order>().Where(it => it.Name.Contains("a")),
|
||||
db.Queryable<Order>().Where(it => it.Name.Contains("b"))
|
||||
).ToList();
|
||||
|
||||
|
||||
|
||||
var query4 = db.Queryable<Order,OrderItem,Custom>(
|
||||
db.Queryable<Order>().Where(it => it.Name.Contains("a")),
|
||||
db.Queryable<OrderItem>().Where(it => it.CreateTime>DateTime.Now),
|
||||
db.Queryable<Custom>().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<Order>()
|
||||
.InnerJoin<Custom>((o, cus) => o.CustomId == cus.Id)
|
||||
.InnerJoin<OrderItem>((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<Order>()).LeftJoin<OrderItem>((m, i) => m.Id == i.OrderId)
|
||||
.ToList();
|
||||
|
||||
|
||||
var query7 = db.Queryable(db.Queryable<Order>().Select<Order>().MergeTable()).LeftJoin<OrderItem>((m, i) => m.Id == i.OrderId)
|
||||
.ToList();
|
||||
|
||||
|
||||
var query8 = db.Queryable<Order>()
|
||||
.LeftJoin(db.Queryable<Custom>().Where(it=>it.Id==1),(o,i)=>o.CustomId==i.Id)
|
||||
.LeftJoin(db.Queryable<OrderItem>().Where(it=>it.OrderId==2),(o,i,item)=>item.OrderId==o.Id)
|
||||
.LeftJoin(db.Queryable<Order>().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<Order>().Where(it => it.Id == 1).ToList();
|
||||
//id=@id or name like '%'+@name+'%'
|
||||
var list2 = db.Queryable<Order>().Where(it => it.Id == 1 || it.Name.Contains("jack")).ToList();
|
||||
|
||||
|
||||
//Create expression
|
||||
var exp = Expressionable.Create<Order>()
|
||||
.And(it => it.Id == 1)
|
||||
.Or(it => it.Name.Contains("jack")).ToExpression();
|
||||
var list3 = db.Queryable<Order>().Where(exp).ToList();
|
||||
|
||||
|
||||
/*** By sql***/
|
||||
|
||||
//id=@id
|
||||
var list4 = db.Queryable<Order>().Where("id=@id", new { id = 1 }).ToList();
|
||||
//id=@id or name like '%'+@name+'%'
|
||||
var list5 = db.Queryable<Order>().Where("id=@id or name like '%'+@name+'%' ", new { id = 1, name = "jack" }).ToList();
|
||||
|
||||
|
||||
|
||||
/*** By dynamic***/
|
||||
|
||||
//id=1
|
||||
var conModels = new List<IConditionalModel>();
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
|
||||
var student = db.Queryable<Order>().Where(conModels).ToList();
|
||||
|
||||
//Complex use case
|
||||
List<IConditionalModel> Order = new List<IConditionalModel>();
|
||||
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<KeyValuePair<WhereType, SqlSugar.ConditionalModel>>()// (id=1 or id=2 and id=1)
|
||||
{
|
||||
//new KeyValuePair<WhereType, ConditionalModel>( WhereType.And ,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" }),
|
||||
new KeyValuePair<WhereType, ConditionalModel> (WhereType.Or,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" }),
|
||||
new KeyValuePair<WhereType, ConditionalModel> ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" })
|
||||
}
|
||||
});
|
||||
var list6 = db.Queryable<Order>().Where(conModels).ToList();
|
||||
|
||||
/*** Conditional builder ***/
|
||||
|
||||
// use whereif
|
||||
string name = "";
|
||||
int id = 1;
|
||||
var query = db.Queryable<Order>()
|
||||
.WhereIF(!string.IsNullOrEmpty(name), it => it.Name.Contains(name))
|
||||
.WhereIF(id > 0, it => it.Id == id).ToList();
|
||||
//clone new Queryable
|
||||
var query2 = db.Queryable<Order>().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<Order>().FirstAsync();
|
||||
task1.Wait();
|
||||
var task2 = db.Queryable<Order>().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)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
118
Src/Asp.Net/AccessTest/Demo/Demo2_Updateable.cs
Normal file
118
Src/Asp.Net/AccessTest/Demo/Demo2_Updateable.cs
Normal file
@@ -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<Order> {
|
||||
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<Class>
|
||||
|
||||
//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<Class> by id
|
||||
|
||||
//Re set value
|
||||
var result66 = db.Updateable(new List<Order> { updateObj }).ReSetValue(it => it.Id = 112).IgnoreColumns(it => new { it.CreateTime, it.Price }).ExecuteCommand();
|
||||
|
||||
|
||||
|
||||
/*** 2.by expression ***/
|
||||
|
||||
//update name,createtime
|
||||
var result7 = db.Updateable<Order>(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand();
|
||||
var result71 = db.Updateable<Order>().SetColumns(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand();
|
||||
//only update name
|
||||
var result8 = db.Updateable<Order>(it => it.Name == "Name" + "1").Where(it => it.Id == 1).ExecuteCommand();
|
||||
var result81 = db.Updateable<Order>().SetColumns(it => it.Name == "Name" + "1").Where(it => it.Id == 1).ExecuteCommand();
|
||||
//
|
||||
|
||||
|
||||
|
||||
|
||||
/*** 3.by Dictionary ***/
|
||||
var dt = new Dictionary<string, object>();
|
||||
dt.Add("id", 1);
|
||||
dt.Add("name", "abc");
|
||||
dt.Add("createTime", DateTime.Now);
|
||||
var dtList = new List<Dictionary<string, object>>();
|
||||
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<Order>(a => a.Name == "a")
|
||||
.Where(a => SqlFunc.StartsWith(a.Name, levelCode))
|
||||
.AddQueue();
|
||||
db.SaveQueues();
|
||||
|
||||
var dataTable = db.Queryable<Order>().Select("id,name,1 as price").Take(2).ToDataTable();
|
||||
db.Fastest<Order>().BulkUpdate("Order", dataTable,new string[] {"id" },new string[] {"name" });
|
||||
Console.WriteLine("#### Updateable End ####");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
331
Src/Asp.Net/AccessTest/Demo/Demo3_Insertable.cs
Normal file
331
Src/Asp.Net/AccessTest/Demo/Demo3_Insertable.cs
Normal file
@@ -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<Order> {
|
||||
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<Order> {
|
||||
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<Order>().Take(5).ToDataTable();
|
||||
dt.TableName = "Order";
|
||||
db.Insertable(dt).UseSqlServer().ExecuteBulkCopy();
|
||||
db.CodeFirst.InitTables<RootTable0, TwoItem, TwoItem2, TwoItem3>();
|
||||
db.CodeFirst.InitTables<ThreeItem2>();
|
||||
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<OrderItem>() {
|
||||
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<RootTable0>() {
|
||||
new RootTable0()
|
||||
{
|
||||
Name="aa",
|
||||
TwoItem2=new TwoItem2() {
|
||||
Id="1",
|
||||
ThreeItem2=new List<ThreeItem2>(){
|
||||
new ThreeItem2(){ Name="a", TwoItem2Id="1" },
|
||||
new ThreeItem2(){ Id=2, Name="a2", TwoItem2Id="2" }
|
||||
}
|
||||
},
|
||||
TwoItem=new TwoItem()
|
||||
{
|
||||
Name ="itema" ,
|
||||
RootId=2
|
||||
},
|
||||
TwoItem3=new List<TwoItem3>(){
|
||||
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<TwoItem3>(){
|
||||
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<SubInsertTree>() {
|
||||
new SubInsertTree(){
|
||||
Expression=it.TwoItem2.ThreeItem2.First().TwoItem2Id
|
||||
}
|
||||
}
|
||||
})
|
||||
.AddSubList(it => it.TwoItem3)
|
||||
.ExecuteCommand();
|
||||
|
||||
SubNoIdentity(db);
|
||||
SubIdentity(db);
|
||||
|
||||
|
||||
var dict = new Dictionary<string, object>();
|
||||
dict.Add("name", "1");
|
||||
dict.Add("CreateTime", DateTime.Now);
|
||||
dict.Add("Price", 1);
|
||||
db.Insertable(dict).AS("[Order]").ExecuteCommand();
|
||||
|
||||
|
||||
db.Fastest<Order>().BulkCopy(insertObjs);
|
||||
|
||||
|
||||
var dataTable= db.Queryable<Order>().Select("id,name,Price").Take(2).ToDataTable();
|
||||
int result= db.Fastest<Order>().BulkCopy("order", dataTable);
|
||||
Console.WriteLine("#### Insertable End ####");
|
||||
|
||||
}
|
||||
|
||||
private static void SubNoIdentity(SqlSugarClient db)
|
||||
{
|
||||
db.CodeFirst.InitTables<Country, Province, City>();
|
||||
db.DbMaintenance.TruncateTable("Country");
|
||||
db.DbMaintenance.TruncateTable("Province");
|
||||
db.DbMaintenance.TruncateTable("City");
|
||||
db.Insertable(new List<Country>()
|
||||
{
|
||||
new Country(){
|
||||
Id=1,
|
||||
Name="中国",
|
||||
Provinces=new List<Province>(){
|
||||
new Province{
|
||||
Id=1001,
|
||||
Name="江苏",
|
||||
citys=new List<City>(){
|
||||
new City(){ Id=1001001, Name="南通" },
|
||||
new City(){ Id=1001002, Name="南京" }
|
||||
}
|
||||
},
|
||||
new Province{
|
||||
Id=1002,
|
||||
Name="上海",
|
||||
citys=new List<City>(){
|
||||
new City(){ Id=1002001, Name="徐汇" },
|
||||
new City(){ Id=1002002, Name="普陀" }
|
||||
}
|
||||
},
|
||||
new Province{
|
||||
Id=1003,
|
||||
Name="北京",
|
||||
citys=new List<City>(){
|
||||
new City(){ Id=1003001, Name="北京A" },
|
||||
new City(){ Id=1003002, Name="北京B" }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
new Country(){
|
||||
Name="美国",
|
||||
Id=2,
|
||||
Provinces=new List<Province>()
|
||||
{
|
||||
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<SubInsertTree>() {
|
||||
new SubInsertTree(){
|
||||
Expression=it.Provinces.First().citys.First().ProvinceId
|
||||
}
|
||||
}
|
||||
})
|
||||
.ExecuteCommand();
|
||||
|
||||
var list = db.Queryable<Country>()
|
||||
.Mapper(it => it.Provinces, it => it.Provinces.First().CountryId)
|
||||
.Mapper(it =>
|
||||
{
|
||||
foreach (var item in it.Provinces)
|
||||
{
|
||||
item.citys = db.Queryable<City>().Where(y => y.ProvinceId == item.Id).ToList();
|
||||
}
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
private static void SubIdentity(SqlSugarClient db)
|
||||
{
|
||||
db.CodeFirst.InitTables<Country1, Province1, City1>();
|
||||
db.DbMaintenance.TruncateTable("Country1");
|
||||
db.DbMaintenance.TruncateTable("Province1");
|
||||
db.DbMaintenance.TruncateTable("City1");
|
||||
db.Insertable(new List<Country1>()
|
||||
{
|
||||
new Country1(){
|
||||
Id=1,
|
||||
Name="中国",
|
||||
Provinces=new List<Province1>(){
|
||||
new Province1{
|
||||
Id=1001,
|
||||
Name="江苏",
|
||||
citys=new List<City1>(){
|
||||
new City1(){ Id=1001001, Name="南通" },
|
||||
new City1(){ Id=1001002, Name="南京" }
|
||||
}
|
||||
},
|
||||
new Province1{
|
||||
Id=1002,
|
||||
Name="上海",
|
||||
citys=new List<City1>(){
|
||||
new City1(){ Id=1002001, Name="徐汇" },
|
||||
new City1(){ Id=1002002, Name="普陀" }
|
||||
}
|
||||
},
|
||||
new Province1{
|
||||
Id=1003,
|
||||
Name="北京",
|
||||
citys=new List<City1>(){
|
||||
new City1(){ Id=1003001, Name="北京A" },
|
||||
new City1(){ Id=1003002, Name="北京B" }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
new Country1(){
|
||||
Name="美国",
|
||||
Id=2,
|
||||
Provinces=new List<Province1>()
|
||||
{
|
||||
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<SubInsertTree>() {
|
||||
new SubInsertTree(){
|
||||
Expression=it.Provinces.First().citys.First().ProvinceId
|
||||
}
|
||||
}
|
||||
})
|
||||
.ExecuteCommand();
|
||||
|
||||
var list = db.Queryable<Country1>()
|
||||
.Mapper(it => it.Provinces, it => it.Provinces.First().CountryId)
|
||||
.Mapper(it =>
|
||||
{
|
||||
foreach (var item in it.Provinces)
|
||||
{
|
||||
item.citys = db.Queryable<City1>().Where(y => y.ProvinceId == item.Id).ToList();
|
||||
}
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
59
Src/Asp.Net/AccessTest/Demo/Demo4_Deleteable.cs
Normal file
59
Src/Asp.Net/AccessTest/Demo/Demo4_Deleteable.cs
Normal file
@@ -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<Order>().Where(new Order() { Id = 1111 }).ExecuteCommand();
|
||||
|
||||
//by primary key
|
||||
db.Deleteable<Order>().In(1111).ExecuteCommand();
|
||||
|
||||
//by primary key array
|
||||
db.Deleteable<Order>().In(new int[] { 1111, 2222 }).ExecuteCommand();
|
||||
|
||||
//by expression
|
||||
db.Deleteable<Order>().Where(it => it.Id == 11111).ExecuteCommand();
|
||||
|
||||
//logic delete
|
||||
db.CodeFirst.InitTables<LogicTest>();
|
||||
;
|
||||
db.Deleteable<LogicTest>().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; }
|
||||
}
|
||||
}
|
36
Src/Asp.Net/AccessTest/Demo/Demo5_SqlQueryable.cs
Normal file
36
Src/Asp.Net/AccessTest/Demo/Demo5_SqlQueryable.cs
Normal file
@@ -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<Order>("select * from [order]").ToPageList(1, 2, ref total);
|
||||
|
||||
|
||||
//by expression
|
||||
var list2 = db.SqlQueryable<Order>("select * from [order]").Where(it => it.Id == 1).ToPageList(1, 2);
|
||||
//by sql
|
||||
var list3 = db.SqlQueryable<Order>("select * from [order]").Where("id=@id", new { id = 1 }).ToPageList(1, 2);
|
||||
|
||||
Console.WriteLine("#### SqlQueryable End ####");
|
||||
}
|
||||
}
|
||||
}
|
53
Src/Asp.Net/AccessTest/Demo/Demo6_Queue.cs
Normal file
53
Src/Asp.Net/AccessTest/Demo/Demo6_Queue.cs
Normal file
@@ -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<Order>(new Order() { Name = "a" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "b" }).AddQueue();
|
||||
db.SaveQueues();
|
||||
|
||||
|
||||
db.Insertable<Order>(new Order() { Name = "a" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "b" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "c" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "d" }).AddQueue();
|
||||
var ar = db.SaveQueuesAsync();
|
||||
ar.Wait();
|
||||
|
||||
db.Queryable<Order>().AddQueue();
|
||||
db.Queryable<Order>().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<Order, Order, Order>();
|
||||
|
||||
Console.WriteLine("#### Queue End ####");
|
||||
}
|
||||
}
|
||||
}
|
78
Src/Asp.Net/AccessTest/Demo/Demo7_Ado.cs
Normal file
78
Src/Asp.Net/AccessTest/Demo/Demo7_Ado.cs
Normal file
@@ -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<SugarParameter>(){
|
||||
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<Order>("select * from [order] ");
|
||||
var list2 = db.Ado.SqlQuery<Order, Order>("select * from [order] where 1=2;select * from [order] ");
|
||||
var list3 = db.Ado.SqlQuery<int>(" delete from [order] where 2=15 ");
|
||||
var intValue = db.Ado.SqlQuerySingle<int>("select 1");
|
||||
db.Ado.ExecuteCommand("delete [order] where id>1000");
|
||||
|
||||
db.SqlQueryable<Custom>(@"select *
|
||||
from custom").ToList();
|
||||
//db.Ado.xxx
|
||||
Console.WriteLine("#### Ado End ####");
|
||||
}
|
||||
}
|
||||
}
|
69
Src/Asp.Net/AccessTest/Demo/Demo8_Saveable.cs
Normal file
69
Src/Asp.Net/AccessTest/Demo/Demo8_Saveable.cs
Normal file
@@ -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<Order>(new Order() { Id=1, Name="jack" }).ToStorage();
|
||||
x.AsUpdateable.ExecuteCommand();
|
||||
x.AsInsertable.ExecuteCommand();
|
||||
|
||||
|
||||
var x2 = db.Storageable<Order>(new Order() { Id = 0, Name = "jack" }).ToStorage();
|
||||
x2.BulkCopy();
|
||||
x2.BulkUpdate();
|
||||
|
||||
var dt = db.Queryable<Order>().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 ####");
|
||||
}
|
||||
}
|
||||
}
|
46
Src/Asp.Net/AccessTest/Demo/Demo9_EntityMain.cs
Normal file
46
Src/Asp.Net/AccessTest/Demo/Demo9_EntityMain.cs
Normal file
@@ -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<Order>();
|
||||
foreach (var column in entityInfo.Columns)
|
||||
{
|
||||
Console.WriteLine(column.DbColumnName);
|
||||
}
|
||||
|
||||
var dbColumnsName = db.EntityMaintenance.GetDbColumnName<EntityMapper>("Name");
|
||||
|
||||
var dbTableName = db.EntityMaintenance.GetTableName<EntityMapper>();
|
||||
|
||||
//more https://github.com/sunkaixuan/SqlSugar/wiki/9.EntityMain
|
||||
Console.WriteLine("#### EntityMain End ####");
|
||||
}
|
||||
}
|
||||
}
|
42
Src/Asp.Net/AccessTest/Demo/DemoA_DbMain.cs
Normal file
42
Src/Asp.Net/AccessTest/Demo/DemoA_DbMain.cs
Normal file
@@ -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 ####");
|
||||
}
|
||||
}
|
||||
}
|
77
Src/Asp.Net/AccessTest/Demo/DemoB_Aop.cs
Normal file
77
Src/Asp.Net/AccessTest/Demo/DemoB_Aop.cs
Normal file
@@ -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<string, SugarParameter[]>(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<Order>().ToList();
|
||||
db.Queryable<OrderItem>().ToList();
|
||||
|
||||
//OnDiffLogEvent
|
||||
var data = db.Queryable<Order>().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<Order>().SetColumns(it=>it.Name=="asdfa").Where(it=>it.Id==1).EnableDiffLogEvent("--update Order--").ExecuteCommand();
|
||||
|
||||
db.Updateable<Order>().SetColumns(it => it.Name == "asdfa")
|
||||
.Where(it =>SqlFunc.Subqueryable<Order>().Where(x=>x.Id==it.Id).Any()).EnableDiffLogEvent("--update Order--").ExecuteCommand();
|
||||
Console.WriteLine("#### Aop End ####");
|
||||
}
|
||||
}
|
||||
}
|
75
Src/Asp.Net/AccessTest/Demo/DemoD_DbFirst.cs
Normal file
75
Src/Asp.Net/AccessTest/Demo/DemoD_DbFirst.cs
Normal file
@@ -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 @" /// <summary>
|
||||
/// Desc_New:{PropertyDescription}
|
||||
/// Default_New:{DefaultValue}
|
||||
/// Nullable_New:{IsNullable}
|
||||
/// </summary>";
|
||||
})
|
||||
.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 ####");
|
||||
}
|
||||
}
|
||||
}
|
40
Src/Asp.Net/AccessTest/Demo/DemoE_CodeFirst.cs
Normal file
40
Src/Asp.Net/AccessTest/Demo/DemoE_CodeFirst.cs
Normal file
@@ -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<CodeFirstTable1>().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; }
|
||||
}
|
||||
}
|
46
Src/Asp.Net/AccessTest/Demo/DemoF_Utilities.cs
Normal file
46
Src/Asp.Net/AccessTest/Demo/DemoF_Utilities.cs
Normal file
@@ -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<int> ids = Enumerable.Range(1, 100).ToList();
|
||||
db.Utilities.PageEach(ids, 10, list =>
|
||||
{
|
||||
Console.WriteLine(string.Join("," ,list));
|
||||
});
|
||||
|
||||
var list2= db.Utilities.DataTableToList<Order>(db.Ado.GetDataTable("select * from [order]"));
|
||||
|
||||
//more https://github.com/sunkaixuan/SqlSugar/wiki/f.Utilities
|
||||
Console.WriteLine("#### Utilities End ####");
|
||||
}
|
||||
}
|
||||
}
|
64
Src/Asp.Net/AccessTest/Demo/DemoG_SimpleClient.cs
Normal file
64
Src/Asp.Net/AccessTest/Demo/DemoG_SimpleClient.cs
Normal file
@@ -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<Order>
|
||||
{
|
||||
public void MyTest()
|
||||
{
|
||||
base.CommQuery("1=1");
|
||||
base.ChangeRepository<Repository<OrderItem>>().CommQuery("1=1");
|
||||
}
|
||||
}
|
||||
public class Repository<T> : SimpleClient<T> 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);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扩展方法,自带方法不能满足的时候可以添加新方法
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<T> CommQuery(string sql)
|
||||
{
|
||||
//base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作
|
||||
return base.Context.Queryable<T>().Where(sql).ToList();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
82
Src/Asp.Net/AccessTest/Demo/DemoH_Tenant.cs
Normal file
82
Src/Asp.Net/AccessTest/Demo/DemoH_Tenant.cs
Normal file
@@ -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<C1Table>
|
||||
{
|
||||
public void Test()
|
||||
{
|
||||
db.BeginTran();
|
||||
base.GetList(); //调用内部仓储方法
|
||||
base.ChangeRepository<Repository<C2Table>>().GetList();//调用外部仓储
|
||||
db.CommitTran();
|
||||
}
|
||||
}
|
||||
public class Repository<T> : SimpleClient<T> where T : class, new()
|
||||
{
|
||||
//单例实同db同上下文共享
|
||||
public static SqlSugarScope db = new SqlSugarScope(new List<ConnectionConfig> {
|
||||
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<TenantAttribute>().configId;
|
||||
Context = db.GetConnection(configId);
|
||||
Context.CodeFirst.InitTables<T>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扩展方法,自带方法不能满足的时候可以添加新方法
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<T> CommQuery(string sql)
|
||||
{
|
||||
//base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作
|
||||
return base.Context.Queryable<T>().Where(sql).ToList();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[TenantAttribute("1")]
|
||||
public class C1Table
|
||||
{
|
||||
public string Id { get; set; }
|
||||
}
|
||||
[TenantAttribute("2")]
|
||||
public class C2Table
|
||||
{
|
||||
public string Id { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
142
Src/Asp.Net/AccessTest/Demo/DemoJ_Report.cs
Normal file
142
Src/Asp.Net/AccessTest/Demo/DemoJ_Report.cs
Normal file
@@ -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<int>() { 1, 2, 3,1,2 };
|
||||
var query1 = db.Queryable<Order>();
|
||||
var queryable2 = db.Reportable(list).ToQueryable<int>();
|
||||
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<OrderItem>().ToList();
|
||||
var query1 = db.Queryable<Order>();
|
||||
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<operateinfo>();
|
||||
db.Deleteable<operateinfo>().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<DateTime>();
|
||||
var queryableRight = db.Queryable<operateinfo>();
|
||||
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()
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Desc:操作序号
|
||||
/// Default:
|
||||
/// Nullable:False
|
||||
/// </summary>
|
||||
public int id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Desc:操作时间
|
||||
/// Default:
|
||||
/// Nullable:False
|
||||
/// </summary>
|
||||
public DateTime operate_time { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Desc:操作类型
|
||||
/// Default:
|
||||
/// Nullable:False
|
||||
/// </summary>
|
||||
public int operate_type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Desc:操作人编号
|
||||
/// Default:
|
||||
/// Nullable:False
|
||||
/// </summary>
|
||||
public int user_id { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
49
Src/Asp.Net/AccessTest/Demo/DemoL_Snowflake.cs
Normal file
49
Src/Asp.Net/AccessTest/Demo/DemoL_Snowflake.cs
Normal file
@@ -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<SnowflakeModel>();
|
||||
Console.WriteLine(db.Queryable<SnowflakeModel>().Count());
|
||||
var id= db.Insertable(new SnowflakeModel()
|
||||
{
|
||||
Name="哈哈"
|
||||
}).ExecuteReturnSnowflakeId();
|
||||
var ids = db.Insertable(db.Queryable<SnowflakeModel>().Take(10).ToList()).ExecuteReturnSnowflakeIdList();
|
||||
Console.WriteLine(db.Queryable<SnowflakeModel>().Count());
|
||||
}
|
||||
}
|
||||
public class SnowflakeModel
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey =true)]
|
||||
public long Id { get; set; }
|
||||
|
||||
public string Name{get;set; }
|
||||
}
|
||||
}
|
72
Src/Asp.Net/AccessTest/Demo/DemoM_UnitOfWork.cs
Normal file
72
Src/Asp.Net/AccessTest/Demo/DemoM_UnitOfWork.cs
Normal file
@@ -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<Order> OrderDal => new DbSet<Order>();
|
||||
public static DbSet<Custom> CustomDal => new DbSet<Custom>();
|
||||
|
||||
|
||||
public class DbSet<T> : SimpleClient<T> where T : class, new()
|
||||
{
|
||||
public DbSet(ISqlSugarClient context = null) : base(context)//需要有构造参数
|
||||
{
|
||||
base.Context = DbContext.Db;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扩展方法,自带方法不能满足的时候可以添加新方法
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<T> CommQuery(string json)
|
||||
{
|
||||
//base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
100
Src/Asp.Net/AccessTest/Demo/DemoN_SplitTable.cs
Normal file
100
Src/Asp.Net/AccessTest/Demo/DemoN_SplitTable.cs
Normal file
@@ -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<OrderSpliteTest>();
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
//根据最近3个表进行查询
|
||||
var list=db.Queryable<OrderSpliteTest>()
|
||||
.SplitTable(DateTime.Now.Date.AddYears(-1),DateTime.Now)
|
||||
.ToList();
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
//根据时间选出的表进行查询
|
||||
var list2 = db.Queryable<OrderSpliteTest>().SplitTable(tabs => tabs.Where(it=> it.Date>=DateTime.Now.AddYears(-2))).ToList();
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
//删除数据只在最近3张表执行操作
|
||||
var x = db.Deleteable<OrderSpliteTest>().Where(it=>it.Pk==Guid.NewGuid()).SplitTable(tabs => tabs.Take(3)).ExecuteCommand();
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
var tableName = db.SplitHelper<OrderSpliteTest>().GetTableName(DateTime.Now.AddDays(-111));
|
||||
|
||||
var listNull= db.Queryable<OrderSpliteTest>().SplitTable(ta => ta.InTableNames(tableName)).ToList();
|
||||
|
||||
var tableName2 = db.SplitHelper(new OrderSpliteTest() { Time=DateTime.Now}).GetTableNames();
|
||||
var tableName3 = db.SplitHelper(new List<OrderSpliteTest> {
|
||||
new OrderSpliteTest() { Time = DateTime.Now },
|
||||
new OrderSpliteTest() { Time = DateTime.Now },
|
||||
new OrderSpliteTest() { Time = DateTime.Now.AddMonths(-10) }
|
||||
}).GetTableNames();
|
||||
var x2 = db.Updateable<OrderSpliteTest>()
|
||||
.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<OrderSpliteTest>().SplitTable().BulkCopy(new List<OrderSpliteTest> {
|
||||
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<OrderSpliteTest>().SplitTable().BulkUpdate(db.Queryable<OrderSpliteTest>().SplitTable(it=>it).ToList());
|
||||
db.Fastest<OrderSpliteTest>().SplitTable().BulkUpdate(db.Queryable<OrderSpliteTest>().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; }
|
||||
}
|
||||
}
|
||||
}
|
108
Src/Asp.Net/AccessTest/Demo/Democ_GobalFilter.cs
Normal file
108
Src/Asp.Net/AccessTest/Demo/Democ_GobalFilter.cs
Normal file
@@ -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<Order>(it => it.Name.Contains("a"),true));
|
||||
|
||||
db.Queryable<Order>().ToList();
|
||||
|
||||
db.Queryable<Order>().ToList();
|
||||
//SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order] WHERE ([Name] like '%'+@MethodConst0+'%')
|
||||
|
||||
//delete Filter
|
||||
db.Deleteable<Order>().EnableQueryFilter().Where(it=>it.Id==1).ExecuteCommand();
|
||||
|
||||
db.Queryable<OrderItem, Order>((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<Order>().Filter(null, false).ToList();
|
||||
//SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order]
|
||||
|
||||
db.Queryable<OrderItem>().LeftJoin<Order>((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<Order>()
|
||||
.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<Order, OrderItem>((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<Order>().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;
|
||||
}
|
||||
}
|
||||
}
|
20
Src/Asp.Net/AccessTest/Models/AttributeTable.cs
Normal file
20
Src/Asp.Net/AccessTest/Models/AttributeTable.cs
Normal file
@@ -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; }
|
||||
}
|
||||
}
|
14
Src/Asp.Net/AccessTest/Models/Custom.cs
Normal file
14
Src/Asp.Net/AccessTest/Models/Custom.cs
Normal file
@@ -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; }
|
||||
}
|
||||
}
|
34
Src/Asp.Net/AccessTest/Models/DataDictionary.cs
Normal file
34
Src/Asp.Net/AccessTest/Models/DataDictionary.cs
Normal file
@@ -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; }
|
||||
}
|
||||
}
|
15
Src/Asp.Net/AccessTest/Models/EntityMapper.cs
Normal file
15
Src/Asp.Net/AccessTest/Models/EntityMapper.cs
Normal file
@@ -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; }
|
||||
}
|
||||
}
|
56
Src/Asp.Net/AccessTest/Models/Mapper.cs
Normal file
56
Src/Asp.Net/AccessTest/Models/Mapper.cs
Normal file
@@ -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<OrderItem> 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<B> BList { get; set; }
|
||||
}
|
||||
public class B
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
24
Src/Asp.Net/AccessTest/Models/Order.cs
Normal file
24
Src/Asp.Net/AccessTest/Models/Order.cs
Normal file
@@ -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<OrderItem> Items { get; set; }
|
||||
}
|
||||
}
|
20
Src/Asp.Net/AccessTest/Models/OrderItem.cs
Normal file
20
Src/Asp.Net/AccessTest/Models/OrderItem.cs
Normal file
@@ -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; }
|
||||
}
|
||||
}
|
108
Src/Asp.Net/AccessTest/Models/SubInsertTest.cs
Normal file
108
Src/Asp.Net/AccessTest/Models/SubInsertTest.cs
Normal file
@@ -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> 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> 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<Province> 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<City> 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<Province1> 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<City1> 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; }
|
||||
}
|
||||
}
|
17
Src/Asp.Net/AccessTest/Models/TestTree.cs
Normal file
17
Src/Asp.Net/AccessTest/Models/TestTree.cs
Normal file
@@ -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; }
|
||||
}
|
||||
}
|
20
Src/Asp.Net/AccessTest/Models/Tree.cs
Normal file
20
Src/Asp.Net/AccessTest/Models/Tree.cs
Normal file
@@ -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<Tree> Child { get; set; }
|
||||
}
|
||||
}
|
13
Src/Asp.Net/AccessTest/Models/ViewOrder.cs
Normal file
13
Src/Asp.Net/AccessTest/Models/ViewOrder.cs
Normal file
@@ -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; }
|
||||
}
|
||||
}
|
46
Src/Asp.Net/AccessTest/Program.cs
Normal file
46
Src/Asp.Net/AccessTest/Program.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// Set up config.cs file and start directly F5
|
||||
/// 设置Config.cs文件直接F5启动例子
|
||||
/// </summary>
|
||||
/// <param name="args"></param>
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
36
Src/Asp.Net/AccessTest/Properties/AssemblyInfo.cs
Normal file
36
Src/Asp.Net/AccessTest/Properties/AssemblyInfo.cs
Normal file
@@ -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")]
|
@@ -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
|
||||
|
Reference in New Issue
Block a user