first commit

This commit is contained in:
2026-09-02 16:20:27 +08:00
commit 30fd63c673
4410 changed files with 591124 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
+214
View File
@@ -0,0 +1,214 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
build/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
## TODO: Comment the next line if you want to checkin your
## web deploy settings but do note that will include unencrypted
## passwords
#*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# LightSwitch generated files
GeneratedArtifacts/
_Pvt_Extensions/
ModelManifest.xml
Src/Asp.NetCore2/SqlSeverTest/.idea/
.idea
/Src/Asp.NetCore2/SqlSugar.GBaseCore/GBase/GBaseProvider.zip
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 jacktang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+251
View File
@@ -0,0 +1,251 @@
<p align="center">
<span>English</span> |
<a href="https://www.donet5.com/Home/Doc"><font color="red">中文</font></a>
</p>
## SqlSugar ORM
SqlSugar is .NET open source ORM framework, maintained and updated by Fructose Big Data Technology team, the most easy-to-use ORM out of the box
Advantages: [Low code] [High performance] [Super simple] [Comprehensive features] [ Multi-database compatible] [Suitable products]
## Support .NET
.net framework.net core3.1.ne5.net6.net7.net8 .net9 .net10
## Support database
MySql、SqlServer、Sqlite、Oracle 、 postgresql、达梦、Mongodb
人大金仓(国产推荐)、神通数据库、瀚高、Access DB2、DuckDb、Hana、OceanBase
TDengine QuestDb Clickhouse MySqlConnector、华为 GaussDB
南大通用 GBase、MariaDB、Tidb、Odbc、Percona Server,
Amazon Aurora、Azure Database for MySQL、
Google Cloud SQL for MySQL、custom database
## Description
1. Truly achieve zero SQL ORM table building, index and CRUD all support
2. Support.NET millions of big data write, update, subtable and has billions of query statistics mature solutions
3. Support SAAS complete application: cross-database query, audit, tenant sub-database, tenant sub-table and tenant data isolation
4. Support low code + workflow (dynamic class building, dynamic table building, non-entity multi-library compatible with CRUD, JSON TO SQL, custom XML, etc.)
5. Support ValueObject, discriminator, repository, UnitOfWork, DbContext, AOP
## Documentation
|Other |Select | Insert | Update | Delete|
| ----- | --------- | ----------- | ------- |------- |
<a target="_blank" href="https://github.com/donet5/SqlSugar/wiki/NUGET">Nuget</a>| <a href="https://github.com/DotNetNext/SqlSugar/wiki/1.1--Query‐Simple">Query</a> | <a target="_blank" href="https://github.com/DotNetNext/SqlSugar/wiki/3.Insert"> Insert </a> |<a target="_blank" href="https://github.com/DotNetNext/SqlSugar/wiki/2.Update">Update</a>| <a target="_blank" href="https://github.com/DotNetNext/SqlSugar/wiki/4.1-Delete">Delete</a> |
<a target="_blank" href="https://github.com/donet5/SqlSugar/wiki"> Start guide</a> | <a target="_bank" href="https://github.com/DotNetNext/SqlSugar/wiki/1.2-Query%E2%80%90Join">Join query </a> |<a href="https://github.com/DotNetNext/SqlSugar/wiki/3.2-Dynamic-Insert">Insert without entity </a> | <a href="https://github.com/DotNetNext/SqlSugar/wiki/2.2-Dynamic-Update">Update without entity</a> | <a href="https://github.com/DotNetNext/SqlSugar/wiki/4.2-Dynamic-Delete"> Delete without entity </a> | |
|<a href="https://www.donet5.com/Home/Doc?typeId=2246">Multiple databases</a> | <a target="_bank" href="https://github.com/DotNetNext/SqlSugar/wiki/1.6-Query%E2%80%90Include">Include query</a>|<a target="_bank" href="https://www.donet5.com/Home/Doc?typeId=2430">Include Insert</a>| <a target="_bank" href="https://www.donet5.com/Home/Doc?typeId=2432">Include Update</a>| <a target="_bank" href="https://www.donet5.com/Home/Doc?typeId=2431">Include Delete</a>
|<a href="https://www.donet5.com/Home/Doc"><font color="red">中文文档</font></a>|<a href="https://www.donet5.com/Home/Doc?typeId=2244">Cross database query</a>|<a href="https://www.donet5.com/Home/Doc?typeId=2420">Insert by json</a>|<a href="https://www.donet5.com/Home/Doc?typeId=2420">Update by json</a>|<a href="https://www.donet5.com/Home/Doc?typeId=2420">Delete by json</a>|
## Feature characteristic
### Feature1 : Join query
Super simple query syntax
```cs
var query = db.Queryable<Order>()
.LeftJoin<Custom> ((o, cus) => o.CustomId == cus.Id)
.LeftJoin<OrderItem> ((o, cus, oritem ) => o.Id == oritem.OrderId)
.LeftJoin<OrderItem> ((o, cus, oritem , oritem2) => o.Id == oritem2.OrderId)
.Where(o => o.Id == 1)
.Select((o, cus) => new ViewOrder { Id = o.Id, CustomName = cus.Name })
.ToList();
```
```sql
SELECT
[o].[Id] AS [Id],
[cus].[Name] AS [CustomName]
FROM
[Order] o
Left JOIN [Custom] cus ON ([o].[CustomId] = [cus].[Id])
Left JOIN [OrderDetail] oritem ON ([o].[Id] = [oritem].[OrderId])
Left JOIN [OrderDetail] oritem2 ON ([o].[Id] = [oritem2].[OrderId])
WHERE
([o].[Id] = @Id0)
```
### Feature2 :Include Query、Insert、Delete and Update
```cs
//Includes
var list=db.Queryable<Test>()
.Includes(x => x.Provinces,x=>x.Citys ,x=>x.Street) //multi-level
.Includes(x => x.ClassInfo)
.ToList();
//Includes+left join
var list5= db.Queryable<Student_004>()
.Includes(x => x.school_001, x => x.rooms)
.Includes(x => x.books)
.LeftJoin<Order>((x, y) => x.Id==y.sid)
.Select((x,y) => new Student_004DTO
{
SchoolId = x.SchoolId,
books = x.books,
school_001 = x.school_001,
Name=y.Name
})
.ToList();
```
### Feature3 : Page query
```cs
int pageIndex = 1;
int pageSize = 20;
int totalCount=0;
var page = db.Queryable<Student>().ToPageList(pageIndex, pageSize, ref totalCount);
```
### Feature4 : Dynamic expression
```cs
var names= new string [] { "a","b"};
Expressionable<Order> exp = new Expressionable<Order>();
foreach (var item in names)
{
exp.Or(it => it.Name.Contains(item.ToString()));
}
var list= db.Queryable<Order>().Where(exp.ToExpression()).ToList();
```
```sql
SELECT [Id],[Name],[Price],[CreateTime],[CustomId]
FROM [Order] WHERE (
([Name] like '%'+ CAST(@MethodConst0 AS NVARCHAR(MAX))+'%') OR
([Name] like '%'+ CAST(@MethodConst1 AS NVARCHAR(MAX))+'%')
)
```
### Feature5 : Multi-tenant transaction
```cs
//Creaate database object
SqlSugarClient db = new SqlSugarClient(new List<ConnectionConfig>()
{
new ConnectionConfig(){ ConfigId="0", DbType=DbType.SqlServer, ConnectionString=Config.ConnectionString, IsAutoCloseConnection=true },
new ConnectionConfig(){ ConfigId="1", DbType=DbType.MySql, ConnectionString=Config.ConnectionString4 ,IsAutoCloseConnection=true}
});
var mysqldb = db.GetConnection("1");//mysql db
var sqlServerdb = db.GetConnection("0");// sqlserver db
db.BeginTran();
mysqldb.Insertable(new Order()
{
CreateTime = DateTime.Now,
CustomId = 1,
Name = "a",
Price = 1
}).ExecuteCommand();
mysqldb.Queryable<Order>().ToList();
sqlServerdb.Queryable<Order>().ToList();
db.CommitTran();
```
### Feature6 : Singleton Pattern
Implement transactions across methods
```CS
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);
};
});
using (var tran = Db.UseTran())
{
new Test2().Insert(XX);
new Test1().Insert(XX);
.....
....
tran.CommitTran();
}
```
### Feature7 : Query filter
```cs
//set filter
db.QueryFilter.Add(new TableFilterItem<Order>(it => it.Name.Contains("a")));
db.Queryable<Order>().ToList();
//SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order] WHERE ([Name] like '%'+@MethodConst0+'%')
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+'%')
```
### Feature8 : Insert or update
insert or update
```cs
Db.Storageable(list2).ExecuteCommand();
Db.Storageable(list2).PageSize(1000).ExecuteCommand();
Db.Storageable(list2).PageSize(1000,exrows=> { }).ExecuteCommand();
```
### Feature9 : Auto split table
Split entity
```cs
[SplitTable(SplitType.Year)]//Table by year (the table supports year, quarter, month, week and day)
[SugarTable("SplitTestTable_{year}{month}{day}")]
public class SplitTestTable
{
[SugarColumn(IsPrimaryKey =true)]
public long Id { get; set; }
public string Name { get; set; }
//When the sub-table field is inserted, which table will be inserted according to this field.
//When it is updated and deleted, it can also be convenient to use this field to
//find out the related table
[SplitField]
public DateTime CreateTime { get; set; }
}
```
Split query
```cs
var lis2t = db.Queryable<OrderSpliteTest>()
.SplitTable(DateTime.Now.Date.AddYears(-1), DateTime.Now)
.ToPageList(1,2); 
```
### Feature10 : Big data insert or update
```cs
10.1 BulkCopy
db.Fastest<Order>().BulkCopy(lstData);//insert
db.Fastest<Order>().PageSize(100000).BulkCopy(insertObjs);
db.Fastest<System.Data.DataTable>().AS("order").BulkCopy(dataTable);
10.2 BulkUpdate
db.Fastest<Order>().BulkUpdate(GetList())//update
db.Fastest<Order>().PageSize(100000).BulkUpdate(GetList())
db.Fastest<Order>().BulkUpdate(GetList(),new string[] { "Id"});//no primary key
db.Fastest<Order>().BulkUpdate(GetList(), new string[]{"id"},
new string[]{"name","time"})//Set the updated column
//DataTable
db.Fastest<System.Data.DataTable>().AS("Order").BulkUpdate(dataTable,"Id");//Id is primary key
db.Fastest<System.Data.DataTable>().AS("Order").BulkUpdate(dataTable,"Id",Set the updated column);
10.3 BulkMerge (5.1.4.109)
db.Fastest<Order>().BulkMerge(List);
db.Fastest<Order>().PageSize(100000).BulkMerge(List);
10.4 BulkQuery
db.Queryable<Order>().ToList();//Slightly faster than Dapper
//Suitable for big data export
List<Order> order = new List<Order>();
db.Queryable<Order>().ForEach(it=> { order.Add(it); } ,2000);
10.5 BulkDelete
db.Deleteable<Order>(list).PageSize(1000).ExecuteCommand();
```
@@ -0,0 +1,114 @@
<?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" />
<Compile Include="Unit\UInsert3.cs" />
<Compile Include="Unit\UnitInsertNavN.cs" />
<Compile Include="Unit\UnitOneToOneN.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>
<ItemGroup>
<Content Include="Test.accdb">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="x64\SQLite.Interop.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="x86\SQLite.Interop.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/></startup></configuration>
@@ -0,0 +1,39 @@
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
{
public static string GetCurrentProjectPath
{
get
{
return Environment.CurrentDirectory.Replace(@"\bin\Debug", "");
}
}
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "Provider=Microsoft.ACE.OleDB.16.0;Data Source="+GetCurrentProjectPath+"\\test.accdb";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = ConnectionString;
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = ConnectionString;
}
}
@@ -0,0 +1,451 @@
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.Access,
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.Access,
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
Console.WriteLine(db.CurrentConnectionConfig.IsAutoCloseConnection);
db.CodeFirst.InitTables(typeof(OrderItem));
var id = db.Insertable(new Order() { Name = "order1", CustomId = 1, Price = 0, CreateTime = DateTime.Now }).ExecuteReturnIdentity();
Console.WriteLine(db.CurrentConnectionConfig.IsAutoCloseConnection);
//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.Access,
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.Access,
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.Access, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
// new ConnectionConfig(){ ConfigId="2", DbType=DbType.Access, 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.Access,
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.Access,
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);
}
}
}
@@ -0,0 +1,610 @@
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();
AccessAndSqliteTest();
//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>().ToList();
var getTake = db.Queryable<Order>().Take(2).ToList();
var getSkip = db.Queryable<Order>().Skip(2).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>().OrderBy(it=>it.Id).ToPageList(3,5, 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>()
.OrderBy(o=>o.Id )
.Select(o => new ViewOrder(){
Name=SqlFunc.Subqueryable<Custom>().Where(z=>z.Id==o.CustomId).Select(z=>z.Name)
,Id=o.Id
})
.ToPageList(2,2 );
//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 AccessAndSqliteTest()
{
var db = GetInstance();
var sqlitedb = GetSqliteInstance();
db.Queryable<Order>().ToList();
sqlitedb.DbMaintenance.CreateDatabase();
sqlitedb.CodeFirst.InitTables<Order>();
sqlitedb.Queryable<Order>().ToList();
db.Queryable<Order>().ToList();
}
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.Access,
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)));
}
}
});
}
private static SqlSugarClient GetSqliteInstance()
{
return new SqlSugarClient(new ConnectionConfig()
{
DbType = SqlSugar.DbType.Sqlite,
ConnectionString = "DataSource=/sqlite.db",
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)));
}
}
});
}
}
}
@@ -0,0 +1,119 @@
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.Access,
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(updateObjs).ExecuteCommand();
var result2 = 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 ####");
}
}
}
@@ -0,0 +1,332 @@
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.Access,
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();
var x = db.Insertable(insertObj).IgnoreColumns(it => new { it.CreateTime }).ExecuteReturnIdentity();//get identity
//Ignore CreateTime
var x1= db.Insertable(insertObj).IgnoreColumns(it => new { it.CreateTime }).ExecuteReturnIdentityAsync().GetAwaiter().GetResult();//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).ExecuteCommand();
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();
}
}
}
@@ -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.Access,
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; }
}
}
@@ -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.Access,
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 ####");
}
}
}
@@ -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.Access,
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 ####");
}
}
}
@@ -0,0 +1,57 @@
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.Access,
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" });
//There are many methods to under db.ado
var list = db.Ado.SqlQuery<Order>("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 from [order] where id>1000");
db.SqlQueryable<Custom>(@"select *
from custom").ToList();
//db.Ado.xxx
Console.WriteLine("#### Ado End ####");
}
}
}
@@ -0,0 +1,55 @@
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.Access,
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=159, Name="jack" }).ToStorage();
var updateRow=x.AsUpdateable.ExecuteCommand();
x.AsInsertable.ExecuteCommand();
var x2 = db.Storageable<Order>(new Order() { Id = 0, Name = "jack" }).ToStorage();
var updateRow2 = x2.AsUpdateable.ExecuteCommand();
x2.AsInsertable.ExecuteCommand();
var orders = new List<Order>()
{
new Order() { Id = 0, Name = "jack" },
new Order() { Id = 0, Name = "jack" }
};
var x3 = db.Storageable(orders).ExecuteCommand();
// db.Saveable(new Order() { Id = 159, Name = "jack" }).ExecuteCommand();
Console.WriteLine("");
Console.WriteLine("#### Saveable End ####");
}
}
}
@@ -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.Access,
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 ####");
}
}
}
@@ -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.Access,
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 ####");
}
}
}
@@ -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.Access,
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 ####");
}
}
}
@@ -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.Access,
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 ####");
}
}
}
@@ -0,0 +1,47 @@
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.Access,
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();
db.CodeFirst.InitTables<DateTimeTest2>();
db.Insertable(new DateTimeTest2() { }).ExecuteCommand();
Console.WriteLine("#### CodeFirst end ####");
}
}
public class DateTimeTest2
{
[SugarColumn(IsNullable =true)]
public DateTime? dt { get; set; }
}
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; }
}
}
@@ -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.Access,
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 ####");
}
}
}
@@ -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.Access,
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();
}
}
}
}
@@ -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.Access,
IsAutoCloseConnection = true,
ConnectionString = Config.ConnectionString
},
new ConnectionConfig()
{
ConfigId="2",
DbType = SqlSugar.DbType.Access,
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; }
}
}
}
@@ -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.Access,
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; }
}
}
}
@@ -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.Access,
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; }
}
}
@@ -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.Access,
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;
}
}
}
}
}
@@ -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.Access,
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; }
}
}
}
@@ -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.Access, 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;
}
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -0,0 +1,30 @@
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)
{
DemoE_CodeFirst.Init();
Demo0_SqlSugarClient.Init();
Demo1_Queryable.Init();
Demo2_Updateable.Init();
Demo3_Insertable.Init();
Demo4_Deleteable.Init();
Demo5_SqlQueryable.Init();
Demo8_Saveable.Init();
Demo7_Ado.Init();
DemoD_DbFirst.Init();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
@@ -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")]
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,68 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
internal class UInsert3
{
public static void Init()
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,//Master Connection
DbType = DbType.Access,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
db.CodeFirst.InitTables<Order1>();
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars));//输出sql,查看执行sql 性能无影响
};
db.Insertable(new Order1() { Name = "a" }).ExecuteCommand();
db.Insertable(new List<Order1>() {
new Order1() { Name = "a" },
new Order1() { Name = "a" }
}).ExecuteCommand();
db.Insertable(new ORDER1() { Name = "a" }).ExecuteCommand();
}
public class Order1
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
public decimal Price { get; set; }
[SugarColumn(InsertServerTime =true)]
public DateTime CreateTime { get; set; }
[SugarColumn(IsNullable = true)]
public int CustomId { get; set; }
}
public class ORDER1
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
public decimal Price { get; set; }
[SugarColumn(InsertSql = "'2020-1-1'")]
public DateTime CreateTime { get; set; }
[SugarColumn(IsNullable = true)]
public int CustomId { get; set; }
}
}
}
@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
namespace OrmTest
{
public class UnitInsertNavN
{
public static void Init()
{
//导航更新问题
//关联层级大于或等于四层时 存在脏数据
Console.WriteLine("----------程序开始----------");
//创建数据库对象
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,//Master Connection
DbType = DbType.Access,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType,sql,pars));//输出sql,查看执行sql 性能无影响
};
//如果不存在创建数据库存在不会重复创建
//db.DbMaintenance.CreateDatabase();
//根据实体名创建对应表
db.CodeFirst.InitTables(typeof(ClassA), typeof(ClassB));
//清空表中数据
db.Deleteable<ClassA>().ExecuteCommand();
db.Deleteable<ClassB>().ExecuteCommand();
//初始化数据 共四层 都是一对多的关系表
ClassA a = new ClassA();
a.AId =1;
a.UpdateTime= DateTime.Now;
ClassB b = new ClassB();
b.BId = 2;
b.AId = a.AId;
a.B = new List<ClassB>() { b };
//导航插入四表数据
db.InsertNav(a)
.Include(t => t.B)
.ExecuteCommand();
var list= db.Queryable<ClassA>().ToList();
var list2=db.Queryable<ClassA>().Includes(z => z.B).ToList();
if (list2.Count == 0)
{
throw new Exception("unit error");
}
Console.WriteLine("----------程序结束----------");
}
/// <summary>
/// 一级类
/// </summary>
[SugarTable("tb_a1")]
public class ClassA
{
[SugarColumn(IsPrimaryKey = true,IsIdentity =true)]
public int AId { get; set; }
[Navigate(NavigateType.OneToMany, nameof(ClassB.AId))]
public List<ClassB> B { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime? UpdateTime { get; set; }
}
/// <summary>
/// 二级类
/// </summary>
[SugarTable("tb_b2")]
public class ClassB
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int BId { get; set; }
public int AId { get; set; }
}
}
}
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
namespace OrmTest
{
public class UnitOneToOneN
{
public static void Init()
{
//创建数据库对象
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,//Master Connection
DbType = DbType.Access,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars));//输出sql,查看执行sql 性能无影响
};
//建表
if (!db.DbMaintenance.IsAnyTable("StudentA", false))
{
db.CodeFirst.InitTables<StudentA>();
}
if (!db.DbMaintenance.IsAnyTable("SchoolA", false))
{
db.CodeFirst.InitTables<SchoolA>();
}
if (!db.DbMaintenance.IsAnyTable("RoomA", false))
{
db.CodeFirst.InitTables<RoomA>();
}
db.Deleteable<StudentA>().ExecuteCommand();
db.Deleteable<SchoolA>().ExecuteCommand();
db.Insertable(new StudentA() { SchoolNo = 100, StudentId = 0 }).ExecuteCommand();
db.Insertable(new SchoolA() { SchoolId = 100, RoomId = 1 }).ExecuteCommand();
//用例代码
var result = db.Queryable<StudentA>()
.Includes(x => x.School)
.ToList();
if (result.First().School==null)
{
throw new Exception("unit error");
}
}
public class StudentA
{
[SugarColumn(IsPrimaryKey = true)]
public int StudentId { get; set; }
public int SchoolNo { get; set; }
[Navigate(NavigateType.OneToOne, nameof(SchoolNo) )]
public SchoolA School { get; set; }
}
public class SchoolA
{
[SugarColumn(IsPrimaryKey = true)]
public int SchoolId { get; set; }
public int SchoolNo { get; set; }
public int RoomId { get; set; }
[Navigate(NavigateType.OneToOne, nameof(RoomId))]
public RoomA Room { get; set; }
}
public class RoomA
{
[SugarColumn(IsPrimaryKey = true)]
public int RoomId { get; set; }
}
}
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
@@ -0,0 +1,39 @@
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
{
public static string GetCurrentProjectPath
{
get
{
return Environment.CurrentDirectory.Replace(@"\bin\Debug", "");
}
}
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "Provider=Microsoft.ACE.OleDB.16.0;Data Source="+GetCurrentProjectPath+"\\test.accdb";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = ConnectionString;
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = ConnectionString;
}
}
@@ -0,0 +1,89 @@
<?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>{7BAAEBFC-D86E-4127-8640-E7EFAB8F40EA}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>CustomDbTest</RootNamespace>
<AssemblyName>CustomDbTest</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="Demo0_SqlSugarClient.cs" />
<Compile Include="Demo1_Queryable.cs" />
<Compile Include="Demo2_Updateable.cs" />
<Compile Include="Demo3_Insertable.cs" />
<Compile Include="Demo4_Deleteable.cs" />
<Compile Include="Demo5_SqlQueryable.cs" />
<Compile Include="Demo7_Ado.cs" />
<Compile Include="DemoD_DbFirst.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" />
</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>
<ItemGroup>
<Content Include="Test.accdb">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,454 @@
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.Custom,
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.Custom,
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.Custom,
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.Custom,
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.Custom, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
// new ConnectionConfig(){ ConfigId="2", DbType=DbType.Custom, 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.Custom,
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.Custom,
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);
}
}
}
@@ -0,0 +1,573 @@
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>().ToList();
var getTake = db.Queryable<Order>().Take(2).ToList();
var getSkip = db.Queryable<Order>().Skip(2).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>().OrderBy(it=>it.Id).ToPageList(3,5, 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.Custom,
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)));
}
}
});
}
}
}
@@ -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.Custom,
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 ####");
}
}
}
@@ -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.Custom,
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();
}
}
}
@@ -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.Custom,
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; }
}
}
@@ -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.Custom,
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 ####");
}
}
}
@@ -0,0 +1,57 @@
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.Custom,
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" });
//There are many methods to under db.ado
var list = db.Ado.SqlQuery<Order>("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 from [order] where id>1000");
db.SqlQueryable<Custom>(@"select *
from custom").ToList();
//db.Ado.xxx
Console.WriteLine("#### Ado End ####");
}
}
}
@@ -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.Custom,
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 ####");
}
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}
@@ -0,0 +1,37 @@
using SqlSugar;
using System;
using System.Reflection;
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)
{
//Set Custom Db
InstanceFactory.CustomDbName = "Access";
InstanceFactory.CustomDllName = "SqlSugar.Access";
InstanceFactory.CustomAssemblies =
new Assembly[] { typeof(SqlSugar.Access.AccessProvider).Assembly };
InstanceFactory.CustomNamespace = "SqlSugar.Access";
Demo0_SqlSugarClient.Init();
Demo1_Queryable.Init();
Demo2_Updateable.Init();
Demo3_Insertable.Init();
Demo4_Deleteable.Init();
Demo5_SqlQueryable.Init();
Demo7_Ado.Init();
DemoD_DbFirst.Init();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CustomDbTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomDbTest")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7baaebfc-d86e-4127-8640-e7efab8f40ea")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Binary file not shown.
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
</configuration>
@@ -0,0 +1,45 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest.Test
{
public class BugTest1
{
public static void Init()
{
SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.Dm,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
});
//调式代码 用来打印SQL
Db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql);
};
Db.CodeFirst.InitTables(typeof(testmmxxxmm121));
var id = Guid.NewGuid();
Db.Insertable(new testmmxxxmm121() { x = id }).ExecuteCommand();
var x= Db.Queryable<testmmxxxmm121>().Where(it => it.x.ToString().ToUpper() == id.ToString().ToUpper()).ToList();
}
}
public class testmmxxxmm121
{
[SugarColumn(IsPrimaryKey =true,IsIdentity =true)]
public int id { get; set; }
[SugarColumn(ColumnDataType ="varchar(36)")]
public Guid x { get; set; }
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
/// <summary>
/// 配置连接字符串后,需要手动建库,表可以自动创建
/// </summary>
public class Config
{
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "Server=153.101.199.83:5236;User Id=SYSDBA;PWD=QwerasdABC;DATABASE=DAMENG";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = ConnectionString;
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = ConnectionString;
}
}
@@ -0,0 +1,416 @@
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.Dm,
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.Dm,
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",new { id=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", FieldValueConvertFunc=it=>Convert.ToInt32(it) });//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.Dm,
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.Dm,
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.Dm, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
new ConnectionConfig(){ ConfigId="2", DbType=DbType.Dm, 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");
var result2 = db.UseTranAsync(() =>
{
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("");
});
result2.Wait();
if (result.IsSuccess == false)
{
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());
}
Console.WriteLine("#### Distributed TransactionExample End ####");
}
}
/// <summary>
/// DbContext Example 1
/// </summary>
public class DbContext
{
public SqlSugarClient Db;
public DbContext()
{
Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.Dm,
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.Dm,
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);
}
}
}
@@ -0,0 +1,353 @@
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();
}
private static void EasyExamples()
{
Console.WriteLine("");
Console.WriteLine("#### Examples Start ####");
var db = GetInstance();
var dbTime = db.GetDate();
var getAll = db.Queryable<Order>().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();
Console.WriteLine("#### Examples End ####");
}
private static void ReturnType()
{
Console.WriteLine("");
Console.WriteLine("#### ReturnType Start ####");
var db = GetInstance();
List<Order> list = db.Queryable<Order>().ToList();
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 list2 = db.Queryable<Order>().Where(it => SqlFunc.Subqueryable<OrderItem>().Where(i => i.OrderId == it.Id).Any()).ToList();
Console.WriteLine("#### Subquery End ####");
}
private static void SqlFuncTest()
{
Console.WriteLine("");
Console.WriteLine("#### SqlFunc Start ####");
var db = GetInstance();
db.Insertable(new Order()
{
CreateTime = DateTime.Now,
Name = "now",
CustomId = 1,
Price = 0
}).ExecuteCommand();
var index= db.Queryable<Order>().Select(it => SqlFunc.CharIndex("a", "cccacc")).First();
var list2 = db.Queryable<Order>().Select(it => new
{
date = SqlFunc.ToDateShort(SqlFunc.GetDate()),
datetime = SqlFunc.GetDate()
}).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();
//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();
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" , FieldValueConvertFunc=it=>Convert.ToInt32(it) });//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", FieldValueConvertFunc = it => Convert.ToInt32(it) });//id=1
//conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Like, FieldValue = "1", FieldValueConvertFunc = it => Convert.ToInt32(it) });// 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" , FieldValueConvertFunc = it => Convert.ToInt32(it) }),
new KeyValuePair<WhereType, ConditionalModel> ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" ,FieldValueConvertFunc = it => Convert.ToInt32(it)})
}
});
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.Dm,
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)));
}
}
});
}
}
}
@@ -0,0 +1,108 @@
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.Dm,
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>
var result21 = db.Updateable(new List<Order>() { }).ExecuteCommand();
//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
/*** 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").Where(it => it.Id == 1).ExecuteCommand();
var result81 = db.Updateable<Order>().SetColumns(it => it.Name == "Name" ).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();
Console.WriteLine("#### Updateable End ####");
}
}
}
@@ -0,0 +1,56 @@
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.Dm,
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 updateObjs = new List<Order> {
new Order() { Id = 11, Name = "order11", Price=0 },
new Order() { Id = 12, Name = "order12" , Price=0}
};
//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(updateObjs).ExecuteCommand();//get change row count
//Use Lock
db.Insertable(insertObj).With(SqlWith.UpdLock).ExecuteCommand();
Console.WriteLine("#### Insertable End ####");
}
}
}
@@ -0,0 +1,48 @@
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.Dm,
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();
Console.WriteLine("#### Deleteable End ####");
}
}
}
@@ -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.Dm,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
int total = 0;
var list = db.SqlQueryable<Student>("select * from \"ORDER\"").ToPageList(1, 2, ref total);
//by expression
var list2 = db.SqlQueryable<Student>("select * from \"ORDER\"").Where(it => it.Id == 1).ToPageList(1, 2);
//by sql
var list3 = db.SqlQueryable<Student>("select * from \"ORDER\"").Where("id=@id", new { id = 1 }).ToPageList(1, 2);
Console.WriteLine("#### SqlQueryable End ####");
}
}
}
@@ -0,0 +1,52 @@
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.Dm,
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 });
var result2 = db.SaveQueues<Order, Order, Order>();
Console.WriteLine("#### Queue End ####");
}
}
}
@@ -0,0 +1,57 @@
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.Dm,
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" });
//Stored Procedure
//var dt3 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", new { name = "张三", age = 0 });
//var nameP = new SugarParameter("@name", "张三");
//var ageP = new SugarParameter("@age", null, true);//isOutput=true
//var dt4 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", nameP, ageP);
//There are many methods to under db.ado
var list= db.Ado.SqlQuery<Order>("select * from \"ORDER\" ");
var intValue=db.Ado.SqlQuerySingle<int>("select 1");
db.Ado.ExecuteCommand("delete from \"ORDER\" where id>@order",new { order=1});
//db.Ado.xxx
Console.WriteLine("#### Ado End ####");
}
}
}
@@ -0,0 +1,48 @@
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.Dm,
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
db.Saveable<Order>(new Order() { Id=1, Name="jack" }).ExecuteReturnEntity();
//insert or update
db.Saveable<Order>(new Order() { Id = 1000, Name = "jack", CreateTime=DateTime.Now })
.InsertColumns(it => new { it.Name,it.CreateTime, it.Price})//if insert into name,CreateTime,Price
.UpdateColumns(it => new { it.Name, it.CreateTime })//if update set name CreateTime
.ExecuteReturnEntity();
Console.WriteLine("");
Console.WriteLine("#### Saveable End ####");
}
}
}
@@ -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.Dm,
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 ####");
}
}
}
@@ -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.Dm,
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 ####");
}
}
}
@@ -0,0 +1,68 @@
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.Dm,
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);
Console.WriteLine(editBeforeData[0].Columns[1].Value);
Console.WriteLine("to");
Console.WriteLine(editAfterData[0].Columns[1].Value);
//Write logic
};
db.Queryable<Order>().ToList();
db.Queryable<OrderItem>().ToList();
//OnDiffLogEvent
var data = db.Queryable<Order>().First();
data.Name = "changeName";
db.Updateable(data).EnableDiffLogEvent("--update Order--").ExecuteCommand();
Console.WriteLine("#### Aop End ####");
}
}
}
@@ -0,0 +1,78 @@
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.Dm,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
MoreSettings=new ConnMoreSettings() {
PgSqlIsAutoToLower=false
}
});
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 ####");
}
}
}
@@ -0,0 +1,97 @@
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.Dm,
ConnectionString = Config.ConnectionString3,
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<CodeFirstDFAAFA>();
db.Insertable(new List<CodeFirstDFAAFA>() {
new CodeFirstDFAAFA(){ timeOffset=DateTimeOffset.Now,timeOffset2=DateTimeOffset.Now },
new CodeFirstDFAAFA() { timeOffset = DateTimeOffset.Now, timeOffset2 = DateTimeOffset.Now }
}).ExecuteCommand();
// db.DbMaintenance.CreateDatabase();
if (db.DbMaintenance.IsAnyTable("CodeFirstTable1", false))
db.DbMaintenance.DropTable("CodeFirstTable1");
if (db.DbMaintenance.IsAnyTable("CodeFirstLong", false))
db.DbMaintenance.DropTable("CodeFirstLong");
db.CodeFirst.InitTables(typeof(CodeFirstTable1));//Create CodeFirstTable1
db.Insertable(new CodeFirstTable1() { Name = "a", Text="a" }).ExecuteCommand();
var list = db.Queryable<CodeFirstTable1>().ToList();
db.CodeFirst.InitTables<CodeFirstLong>();
var tableInfo=db.DbMaintenance.GetColumnInfosByTableName("CodeFirstLong", false);
db.CodeFirst.InitTables<CodeFirstadfafa>();
db.Insertable(new CodeFirstadfafa() { index = "a" }).ExecuteCommand();
db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
{
IsAutoToUpper = false
};
db.CodeFirst.InitTables<CodeFirstNoUpper>();
db.Insertable(new CodeFirstNoUpper() { Id = Guid.NewGuid() + "", Name = "a" }).ExecuteCommand();
var list2= db.Queryable<CodeFirstNoUpper>().Where(it=>it.Id!=null).ToList();
db.Updateable(list2).ExecuteCommand();
db.Deleteable(list2).ExecuteCommand();
db.Updateable(list2.First()).ExecuteCommand();
db.Deleteable<CodeFirstNoUpper>().Where(it => it.Id != null).ExecuteCommand();
db.Updateable<CodeFirstNoUpper>().SetColumns(it=>it.Name=="a").Where(it => it.Id != null).ExecuteCommand();
db.Updateable<CodeFirstNoUpper>().SetColumns(it =>new CodeFirstNoUpper() {
Name="a"
} ).Where(it => it.Id != null).ExecuteCommand();
Console.WriteLine("#### CodeFirst end ####");
}
}
public class CodeFirstDFAAFA
{
public DateTimeOffset timeOffset { get; set; }
[SugarColumn(ColumnDataType = "timestamp with time zone")]
public DateTimeOffset timeOffset2 { get; set; }
}
public class CodeFirstadfafa
{
public string index { get; set; }
}
public class CodeFirstNoUpper
{
[SugarColumn(IsPrimaryKey =true)]
public string Id { get; set; }
public string Name { get; set; }
}
public class CodeFirstLong
{
[SugarColumn(IsPrimaryKey =true,IsIdentity =true)]
public long id { get; set; }
}
public class CodeFirstTable1
{
[SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
public int Id { get; set; }
public string Name { get; set; }
[SugarColumn(ColumnDataType = "varchar(255)")]//custom
public string Text { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime CreateTime { get; set; }
}
}
@@ -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.Dm,
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 ####");
}
}
}
@@ -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 DemoG_SimpleClient
{
public static void Init()
{
Console.WriteLine("");
Console.WriteLine("#### SimpleClient Start ####");
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.Dm,
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)));
}
}
});
Console.WriteLine("#### SimpleClient End ####");
}
}
}
@@ -0,0 +1,101 @@
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.Dm,
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(0));
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; }
[SugarColumn(Length =200)]
public string Name { get; set; }
[SugarColumn(IsNullable =true)]
[SplitField]
public DateTime Time { get; set; }
}
}
}
@@ -0,0 +1,77 @@
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 ####");
var db = GetInstance();
var sql = db.Queryable<Order>().ToSql();
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE isDelete=0
Console.WriteLine(sql);
var sql2 = db.Queryable<Order,OrderItem>((main,ot)=> main.Id==ot.OrderId).ToSql();
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` main ,[OrderDetail] ot WHERE ( [main].[Id] = [ot].[OrderId] ) AND main.isDelete=0
Console.WriteLine(sql2);
var sql3 = db.Queryable<Order>().Filter("Myfilter").ToSql();// Myfilter+Gobal
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE Name='jack' AND isDelete=0
Console.WriteLine(sql3);
var sql4 = db.Queryable<Order>().Filter("Myfilter",isDisabledGobalFilter:true).ToSql();//only Myfilter
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE Name='jack'
Console.WriteLine(sql4);
Console.WriteLine("#### Filter End ####");
}
public static SqlSugarClient GetInstance()
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.Dm, ConnectionString = Config.ConnectionString, IsAutoCloseConnection = true });
//single table query gobal filter
db.QueryFilter.Add(new SqlFilterItem()
{
FilterValue = filterDb =>
{
//Writable logic
return new SqlFilterResult() { Sql = " isDelete=0" };//Global string perform best
}
});
//Multi-table query gobal filter
db.QueryFilter.Add(new SqlFilterItem()
{
FilterValue = filterDb =>
{
//Writable logic
return new SqlFilterResult() { Sql = " main.isDelete=0" };
},
IsJoinQuery=true
});
//Specific filters
db.QueryFilter.Add(new SqlFilterItem()
{
FilterName= "Myfilter",
FilterValue = filterDb =>
{
//Writable logic
return new SqlFilterResult() { Sql = "Name='jack'" };
}
});
return db;
}
}
}
@@ -0,0 +1,111 @@
<?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>{68A45CBA-AD64-429C-9AF4-FE78658B73D5}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>DmTest</RootNamespace>
<AssemblyName>DmTest</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</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="DmProvider, Version=1.1.0.0, Culture=neutral, PublicKeyToken=7a2d44aa446c6d01, processorArchitecture=MSIL">
<HintPath>..\packages\dmdbms.DmProvider.1.1.0.16649\lib\net45\DmProvider.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Transactions" />
<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="BugTest\BugTest1.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\DemoN_SplitTable.cs" />
<Compile Include="Models\Student.cs" />
<Compile Include="Models\AttributeTable.cs" />
<Compile Include="Models\CarType.cs" />
<Compile Include="Models\Custom.cs" />
<Compile Include="Models\EntityMapper.cs" />
<Compile Include="Models\Mapper.cs" />
<Compile Include="Models\MyCustomAttributeTable.cs" />
<Compile Include="Models\Order.cs" />
<Compile Include="Models\OrderItem.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" />
<Compile Include="UnitTest\Main.cs" />
<Compile Include="UnitTest\UAdo.cs" />
<Compile Include="UnitTest\UCodeFirst.cs" />
<Compile Include="UnitTest\UInsert3.cs" />
<Compile Include="UnitTest\UJson.cs" />
<Compile Include="UnitTest\UnitBulkCopy.cs" />
<Compile Include="UnitTest\Updateable.cs" />
<Compile Include="UnitTest\UQueryable.cs" />
<Compile Include="UnitTest\UQueryableAsync.cs" />
<Compile Include="UnitTest\USave.cs" />
<Compile Include="UnitTest\UThread.cs" />
<Compile Include="UnitTest\UThread2.cs" />
<Compile Include="UnitTest\UThread3.cs" />
<Compile Include="UnitTest\UValidate.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj">
<Project>{489bb790-226c-4fad-8d1e-51d72a7ff8e5}</Project>
<Name>SqlSugar</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -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; }
}
}
@@ -0,0 +1,7 @@
namespace OrmTest
{
public class CarType
{
public bool State { get; set; }
}
}
@@ -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; }
}
}
@@ -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; }
}
}

Some files were not shown because too many files have changed in this diff Show More