├── SqlSugarCore
├── src
│ ├── SqlSugarForCore
│ │ ├── nuget.bat
│ │ ├── NuGet.exe
│ │ ├── project.json
│ │ ├── Tool
│ │ │ ├── IStorageObject.cs
│ │ │ ├── Check.cs
│ │ │ ├── JsonConverter.cs
│ │ │ ├── SqlException.cs
│ │ │ ├── IEnumerableExtensions.cs
│ │ │ ├── LanguageHelper.cs
│ │ │ ├── SqlSugarToolCoreDiff.cs
│ │ │ ├── SqlSugarToolExtensions.cs
│ │ │ ├── CacheManager.cs
│ │ │ ├── PubConvert.cs
│ │ │ ├── IsWhatExtensions.cs
│ │ │ └── SqlSugarTool.cs
│ │ ├── PubModel
│ │ │ ├── KeyValue.cs
│ │ │ ├── PubEnum.cs
│ │ │ └── PubModel.cs
│ │ ├── Package.txt
│ │ ├── Core
│ │ │ ├── ResolveExpress
│ │ │ │ ├── Property.cs
│ │ │ │ ├── Models.cs
│ │ │ │ ├── ResolveFieldName.cs
│ │ │ │ ├── Constant.cs
│ │ │ │ ├── ResolveSelect.cs
│ │ │ │ └── Method.cs
│ │ │ └── IDataRecordExtensions.cs
│ │ ├── Properties
│ │ │ └── AssemblyInfo.cs
│ │ ├── SqlSugarForCore.xproj
│ │ ├── Sqlable
│ │ │ └── Sqlable.cs
│ │ ├── SqlSugarForCore.nuspec
│ │ ├── Base
│ │ │ └── TypeExtensions.cs
│ │ ├── Generating
│ │ │ ├── ClassTemplate.cs
│ │ │ └── SugarAttribute.cs
│ │ └── Queryable
│ │ │ └── Queryable.cs
│ └── SqlSugarCore
│ │ ├── Demos
│ │ ├── IDemos.cs
│ │ ├── SerializerDateFormat.cs
│ │ ├── Tran.cs
│ │ ├── Ado.cs
│ │ ├── Delete.cs
│ │ ├── PubMethod.cs
│ │ ├── SqlPageModel.cs
│ │ ├── Log.cs
│ │ ├── EnumDemo.cs
│ │ ├── IgnoreErrorColumns.cs
│ │ ├── MappingColumns.cs
│ │ ├── MappingTable.cs
│ │ ├── SerialNumber.cs
│ │ ├── Insert.cs
│ │ ├── Filter.cs
│ │ ├── Filter2.cs
│ │ ├── CreateClass.cs
│ │ ├── InitConfig.cs
│ │ ├── AttributesMapping.cs
│ │ └── Update.cs
│ │ ├── Models
│ │ ├── StudentGroup.cs
│ │ ├── Area.cs
│ │ ├── Subject.cs
│ │ ├── School.cs
│ │ ├── LanguageTest.cs
│ │ ├── V_LanguageTest.cs
│ │ ├── Student.cs
│ │ ├── TestUpdateColumns.cs
│ │ ├── Student2.cs
│ │ ├── V_Student.cs
│ │ └── InsertTest.cs
│ │ ├── api_cn.htm
│ │ ├── api_en.htm
│ │ ├── project.json
│ │ ├── Properties
│ │ └── AssemblyInfo.cs
│ │ ├── Dao
│ │ └── SugarDao.cs
│ │ ├── SqlSugarTest.xproj
│ │ └── Program.cs
├── global.json
└── SqlSugarCore.sln
├── .gitattributes
└── .gitignore
/SqlSugarCore/src/SqlSugarForCore/nuget.bat:
--------------------------------------------------------------------------------
1 | %~dp0nuget.exe pack %~dp0SqlSugarForCore.nuspec -OutputDirectory %~dp0
--------------------------------------------------------------------------------
/SqlSugarCore/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "projects": [ "src", "test" ],
3 | "sdk": {
4 | "version": "1.0.0-preview2-003131"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/NuGet.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_SqlSugar/HEAD/SqlSugarCore/src/SqlSugarForCore/NuGet.exe
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/IDemos.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | namespace NewTest.Demos
6 | {
7 | public interface IDemos
8 | {
9 | void Init();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/StudentGroup.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Models
7 | {
8 | public class StudentGroup
9 | {
10 | public string Sex { get; set; }
11 | public int Count { get; set; }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/api_cn.htm:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/api_en.htm:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/project.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "1.0.0-*",
3 | "buildOptions": {
4 | "emitEntryPoint": true
5 | },
6 |
7 | "dependencies": {
8 | "Microsoft.NETCore.App": {
9 | "type": "platform",
10 | "version": "1.0.1"
11 | },
12 | "SqlSugarForCore": "1.0.0-*",
13 | "System.Text.Encoding.CodePages": "4.0.1"
14 | },
15 |
16 | "frameworks": {
17 | "netcoreapp1.0": {
18 | "imports": "dnxcore50"
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/Area.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class Area
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int id {get;set;}
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public string name {get;set;}
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/project.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "1.0.0-*",
3 | "dependencies": {
4 | "NETStandard.Library": "1.6.0",
5 | "Newtonsoft.Json": "9.0.1",
6 | "System.Collections.NonGeneric": "4.0.1",
7 | "System.Data.Common": "4.1.0",
8 | "System.Data.SqlClient": "4.1.0",
9 | "System.Dynamic.Runtime": "4.0.11",
10 | "System.Reflection.Emit.Lightweight": "4.0.1"
11 | },
12 | "frameworks": {
13 | "netstandard1.6": {
14 | "imports": "dnxcore50"
15 | }
16 | },
17 | "buildOptions": {
18 | "xmlDoc": true
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/Subject.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class Subject
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int id {get;set;}
16 |
17 | ///
18 | /// Desc:学生ID
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public int? studentId {get;set;}
23 |
24 | ///
25 | /// Desc:-
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public string name {get;set;}
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/School.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class School
8 | {
9 |
10 | ///
11 | /// Desc:地域ID,关联area表
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int id {get;set;}
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public string name {get;set;}
23 |
24 | ///
25 | /// Desc:-
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public int? AreaId {get;set;}
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/LanguageTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class LanguageTest
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int Id {get;set;}
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public int? LanguageId {get;set;}
23 |
24 | ///
25 | /// Desc:-
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public string Name {get;set;}
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/V_LanguageTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class V_LanguageTest
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int Id {get;set;}
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public int? LanguageId {get;set;}
23 |
24 | ///
25 | /// Desc:-
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public string Name {get;set;}
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyConfiguration("")]
9 | [assembly: AssemblyCompany("")]
10 | [assembly: AssemblyProduct("SqlSugarCore")]
11 | [assembly: AssemblyTrademark("")]
12 |
13 | // Setting ComVisible to false makes the types in this assembly not visible
14 | // to COM components. If you need to access a type in this assembly from
15 | // COM, set the ComVisible attribute to true on that type.
16 | [assembly: ComVisible(false)]
17 |
18 | // The following GUID is for the ID of the typelib if this project is exposed to COM
19 | [assembly: Guid("c0888e57-6465-476e-ae60-5d5834f5ec11")]
20 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Tool/IStorageObject.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | namespace SqlSugar
3 | {
4 | ///
5 | /// ** 描述:存储对象接口
6 | /// ** 创始时间:2015-5-29
7 | /// ** 修改时间:-
8 | /// ** 作者:sunkaixuan
9 | ///
10 | internal abstract class IStorageObject
11 | {
12 |
13 | public int Minutes = 60;
14 | public int Hour = 60 * 60;
15 | public int Day = 60 * 60 * 24;
16 | public abstract void Add(string key, V value);
17 | public abstract bool ContainsKey(string key);
18 | public abstract V Get(string key);
19 | public abstract global::System.Collections.Generic.IEnumerable GetAllKey();
20 | public abstract void Remove(string key);
21 | public abstract void RemoveAll();
22 | public abstract void RemoveAll(Func removeExpression);
23 | public abstract V this[string key] { get; }
24 | }
25 | }
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/SerializerDateFormat.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //设置ToJson的日期格式
13 | public class SerializerDateFormat : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动SerializerDateFormat.Init");
19 | using (SqlSugarClient db = SugarDao.GetInstance())
20 | {
21 | db.SerializerDateFormat = "yyyy-mm/dd";
22 | var jsonStr = db.Queryable().OrderBy("id").Take(1).ToJson();
23 | var jsonStr2 = db.Sqlable().From("t").SelectToJson(" top 1 *");
24 | var jsonStr3 = db.SqlQueryJson("select top 1 * from InsertTest");
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/PubModel/KeyValue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | ///
9 | /// 自定义键值类 key is string, value is string
10 | ///
11 | public class KeyValue
12 | {
13 | ///
14 | /// 键
15 | ///
16 | public string Key { get; set; }
17 | ///
18 | /// 值
19 | ///
20 | public string Value { get; set; }
21 | }
22 | ///
23 | /// 自定义键值类 key is string, value is object
24 | ///
25 | public class KeyValueObj
26 | {
27 | ///
28 | /// 键
29 | ///
30 | public string Key { get; set; }
31 | ///
32 | /// 值
33 | ///
34 | public object Value { get; set; }
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Dao/SugarDao.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using SqlSugar;
5 | namespace NewTest.Dao
6 | {
7 | ///
8 | /// SqlSugar
9 | ///
10 | public class SugarDao
11 | {
12 | //禁止实例化
13 | private SugarDao()
14 | {
15 |
16 | }
17 | public static string ConnectionString
18 | {
19 | get
20 | {
21 | string reval = "server=.;uid=sa;pwd=sasa;database=SqlSugarTest"; //这里可以动态根据cookies或session实现多库切换
22 | return reval;
23 | }
24 | }
25 | public static SqlSugarClient GetInstance()
26 | {
27 | var db = new SqlSugarClient(ConnectionString);
28 | db.IsEnableLogEvent = true;//启用日志事件
29 | db.LogEventStarting = (sql, par) => { Console.WriteLine(sql + " " + par+"\r\n"); };
30 | return db;
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Package.txt:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Package
5 | 1.0.0
6 | sunkaixuan
7 | Landa
8 | http://www.apache.org/licenses/LICENSE-2.0.html
9 | http://www.cnblogs.com/sunkaixuan/
10 | http://pic.cnblogs.com/avatar/746906/20150419211858.png
11 | false
12 | Asp.net Core ORM
13 | Copyright 2016
14 | Asp.net core orm
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/Student.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class Student
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int id {get;set;}
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public string name {get;set;}
23 |
24 | ///
25 | /// Desc:学校ID
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public int? sch_id {get;set;}
30 |
31 | ///
32 | /// Desc:-
33 | /// Default:-
34 | /// Nullable:True
35 | ///
36 | public string sex {get;set;}
37 |
38 | ///
39 | /// Desc:-
40 | /// Default:-
41 | /// Nullable:True
42 | ///
43 | public Boolean? isOk {get;set;}
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Core/ResolveExpress/Property.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | //局部类:解析属性
9 | internal partial class ResolveExpress
10 | {
11 | private string GetProMethod(string methodName, string value, bool isField)
12 | {
13 | switch (methodName)
14 | {
15 | case "Length":
16 | return ProLength(value, isField);
17 | default: throw new SqlSugarException(string.Format(ExpNoSupportAttExtMethod, methodName));
18 | }
19 | }
20 | private string ProLength(string value, bool isField)
21 | {
22 | if (isField)
23 | {
24 | return string.Format("LEN({0})", value.GetTranslationSqlName());
25 | }
26 | else
27 | {
28 | return string.Format("{0}", value.ObjToString().Length);
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyConfiguration("作者:孙凯旋,蓝灯软件架构师")]
9 | [assembly: AssemblyCompany("上海蓝灯软件有限公司")]
10 | [assembly: AssemblyProduct("SqlSugarForCore")]
11 | [assembly: AssemblyTrademark("")]
12 |
13 | // Setting ComVisible to false makes the types in this assembly not visible
14 | // to COM components. If you need to access a type in this assembly from
15 | // COM, set the ComVisible attribute to true on that type.
16 | [assembly: ComVisible(false)]
17 |
18 | // The following GUID is for the ID of the typelib if this project is exposed to COM
19 | [assembly: Guid("2ea1a286-e605-4eb8-ba44-c5861e8e552a")]
20 | [assembly: AssemblyVersion("3.5.3.4")]
21 | [assembly: AssemblyFileVersion("3.5.3.4")]
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Tran.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //事务
13 | public class Tran : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动Tran.Init");
19 | using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接
20 | {
21 | db.IsNoLock = true;//启用无锁查询
22 | db.CommandTimeOut = 30000;//设置超时时间
23 | try
24 | {
25 | db.BeginTran();//开启事务
26 | //db.BeginTran(IsolationLevel.ReadCommitted);+3重载可以设置事世隔离级别
27 |
28 | db.CommitTran();//提交事务
29 | }
30 | catch (Exception)
31 | {
32 | db.RollbackTran();//回滚事务
33 | throw;
34 | }
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/TestUpdateColumns.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class TestUpdateColumns
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public Guid VGUID {get;set;}
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:False
21 | ///
22 | public int IdentityField {get;set;}
23 |
24 | ///
25 | /// Desc:-
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public string Name {get;set;}
30 |
31 | ///
32 | /// Desc:-
33 | /// Default:-
34 | /// Nullable:True
35 | ///
36 | public string Name2 {get;set;}
37 |
38 | ///
39 | /// Desc:-
40 | /// Default:-
41 | /// Nullable:True
42 | ///
43 | public DateTime? CreateTime {get;set;}
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/Student2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class Student2
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int id { get; set; }
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public string name { get; set; }
23 |
24 | ///
25 | /// Desc:学校ID
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public int sch_id { get; set; }
30 |
31 | ///
32 | /// Desc:-
33 | /// Default:-
34 | /// Nullable:True
35 | ///
36 | public string sex { get; set; }
37 |
38 | ///
39 | /// Desc:-
40 | /// Default:-
41 | /// Nullable:True
42 | ///
43 | public Boolean isOk { get; set; }
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/SqlSugarForCore.xproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 14.0
5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
6 |
7 |
8 |
9 |
10 | 2ea1a286-e605-4eb8-ba44-c5861e8e552a
11 | SqlSugarForCore
12 | .\obj
13 | .\bin\
14 | v4.5.2
15 |
16 |
17 |
18 | 2.0
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Sqlable/Sqlable.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Data.SqlClient;
6 |
7 | namespace SqlSugar
8 | {
9 | ///
10 | /// ** 描述:Queryable是多表查询基类,基于拥有大量查询扩展函数
11 | /// ** 创始时间:2015-7-13
12 | /// ** 修改时间:-
13 | /// ** 作者:sunkaixuan
14 | /// ** 使用说明:
15 | ///
16 | public class Sqlable
17 | {
18 | ///
19 | /// 数据接口
20 | ///
21 | public SqlSugarClient DB = null;
22 | ///
23 | /// sql临时数据
24 | ///
25 | public StringBuilder Sql { get; set; }
26 | ///
27 | /// Where临时数据
28 | ///
29 | public List Where = new List();
30 | ///
31 | /// OrderBy临时数据
32 | ///
33 | public string OrderBy { get; set; }
34 | ///
35 | /// GroupBy临时数据
36 | ///
37 | public string GroupBy { get; set; }
38 | ///
39 | /// 参数
40 | ///
41 | public List Params = new List();
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/SqlSugarTest.xproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 14.0
5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
6 |
7 |
8 |
9 | c0888e57-6465-476e-ae60-5d5834f5ec11
10 | SqlSugarTest
11 | .\obj
12 | .\bin\
13 | v4.5.2
14 |
15 |
16 | 2.0
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/V_Student.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Models
7 | {
8 | public class V_Student
9 | {
10 |
11 | ///
12 | /// Desc:-
13 | /// Default:-
14 | /// Nullable:False
15 | ///
16 | public int id { get; set; }
17 |
18 | ///
19 | /// Desc:-
20 | /// Default:-
21 | /// Nullable:True
22 | ///
23 | public string name { get; set; }
24 |
25 | ///
26 | /// Desc:学校ID
27 | /// Default:-
28 | /// Nullable:True
29 | ///
30 | public int? sch_id { get; set; }
31 |
32 | ///
33 | /// Desc:-
34 | /// Default:-
35 | /// Nullable:True
36 | ///
37 | public string sex { get; set; }
38 |
39 | ///
40 | /// Desc:-
41 | /// Default:-
42 | /// Nullable:True
43 | ///
44 | public Boolean? isOk { get; set; }
45 |
46 | public string SchoolName { get; set; }
47 |
48 | public string AreaName { get; set; }
49 |
50 | public string SubjectName { get; set; }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Tool/Check.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | ///
9 | /// ** 描述:验证失败,则抛出异常
10 | /// ** 创始时间:2015-7-19
11 | /// ** 修改时间:-
12 | /// ** 作者:sunkaixuan
13 | /// ** 修改人:sunkaixuan
14 | /// ** 使用说明:
15 | ///
16 | public class Check
17 | {
18 | ///
19 | /// 使用导致此异常的参数的名称初始化 System.ArgumentNullException 类的新实例。
20 | ///
21 | ///
22 | ///
23 | public static void ArgumentNullException(object checkObj, string message)
24 | {
25 | if (checkObj == null)
26 | throw new ArgumentNullException(message);
27 | }
28 | ///
29 | /// 使用指定的错误消息初始化 System.Exception 类的新实例。
30 | ///
31 | /// true则引发异常
32 | /// 错误信息
33 | /// 参数
34 | public static void Exception(bool isException, string message, params string[] args)
35 | {
36 | if (isException)
37 | throw new SqlSugarException(string.Format(message, args));
38 | }
39 | }
40 |
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Models/InsertTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Text;
4 |
5 | namespace Models
6 | {
7 | public class InsertTest
8 | {
9 |
10 | ///
11 | /// Desc:-
12 | /// Default:-
13 | /// Nullable:False
14 | ///
15 | public int id {get;set;}
16 |
17 | ///
18 | /// Desc:-
19 | /// Default:-
20 | /// Nullable:True
21 | ///
22 | public string v1 {get;set;}
23 |
24 | ///
25 | /// Desc:-
26 | /// Default:-
27 | /// Nullable:True
28 | ///
29 | public string v2 {get;set;}
30 |
31 | ///
32 | /// Desc:-
33 | /// Default:-
34 | /// Nullable:True
35 | ///
36 | public string v3 {get;set;}
37 |
38 | ///
39 | /// Desc:-
40 | /// Default:-
41 | /// Nullable:True
42 | ///
43 | public int? int1 {get;set;}
44 |
45 | ///
46 | /// Desc:-
47 | /// Default:-
48 | /// Nullable:True
49 | ///
50 | public DateTime? d1 {get;set;}
51 |
52 | ///
53 | /// Desc:-
54 | /// Default:-
55 | /// Nullable:True
56 | ///
57 | public string txt {get;set;}
58 |
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Ado.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 |
9 | namespace NewTest.Demos
10 | {
11 | //完美兼容SqlHelper的所有功能
12 | public class Ado:IDemos
13 | {
14 |
15 | public void Init()
16 | {
17 | Console.WriteLine("启动Ado.Init");
18 | using (var db = SugarDao.GetInstance())
19 | {
20 | var r1 = db.GetDataTable("select * from student");
21 | var r2 = db.GetSingle("select top 1 * from student");
22 | var r3 = db.GetScalar("select count(1) from student");
23 | var r4 = db.GetReader("select count(1) from student");
24 | r4.Dispose();
25 | var r5 = db.GetString("select top 1 name from student");
26 | var r6 = db.ExecuteCommand("select 1");
27 |
28 |
29 | //参数支持
30 | var p1 = db.GetDataTable("select * from student where id=@id", new {id=1 });
31 | var p2 = db.GetDataTable("select * from student where id=@id", new Dictionary() { { "id", "1" } });//目前只支持 Dictionary和Dictionary
32 | var p3 = db.GetDataTable("select * from student where id=@id", new SqlParameter("@id",1) );
33 |
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Delete.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 |
9 | namespace NewTest.Demos
10 | {
11 | //删除的例子
12 | public class Delete:IDemos
13 | {
14 |
15 | public void Init()
16 | {
17 | Console.WriteLine("启动Deletes.Init");
18 | using (var db = SugarDao.GetInstance())
19 | {
20 |
21 |
22 | //删除根据主键
23 | db.Delete(10);
24 |
25 | //删除根据表达示
26 | db.Delete(it => it.id > 100);//支持it=>array.contains(it.id)
27 |
28 | //主键批量删除
29 | db.Delete(new string[] { "100", "101", "102" });
30 |
31 | //非主键批量删除
32 | db.Delete(it => it.name, new string[] { "" });
33 | db.Delete(it => it.id, new int[] { 20, 22 });
34 |
35 |
36 | //根据实体赋值实体一定要有主键,并且要有值。
37 | db.Delete(new School() { id = 200 });
38 |
39 | //根据字符串删除
40 | db.Delete("id=@id", new { id = 100 });
41 |
42 | //假删除
43 | //db.FalseDelete("is_del", 100);
44 | //等同于 update school set is_del=1 where id in(100)
45 | //db.FalseDelete("is_del", it=>it.id==100);
46 |
47 |
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/PubMethod.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 | namespace NewTest.Demos
10 | {
11 | //公用函数
12 | public class PubMethod:IDemos
13 | {
14 |
15 | public void Init()
16 | {
17 | Console.WriteLine("启动PubMethod.Init");
18 | using (var db = SugarDao.GetInstance())
19 | {
20 | //ToJoinSqlInVal
21 | var par = new string[] { "a", "c", "3" };
22 | var ids = par.ToJoinSqlInVal();//将数组转成 'a','c','3' 有防SQL注入处理
23 |
24 |
25 | //ToSqlValue
26 | try
27 | {
28 | var par2 = "a'";
29 | var newpar2 = par2.ToSqlValue();//对字符串防注入处理
30 | }
31 | catch (Exception ex)
32 | {
33 |
34 | Console.WriteLine(ex.Message);
35 | }
36 |
37 | //SqlLikeWordEncode 处理LIKE特殊字符
38 | var likestr = SqlSugarTool.SqlLikeWordEncode("[%%%");
39 |
40 |
41 | //GetParameterArray 获取页面参数所有参数的键和值
42 | var pars = SqlSugarTool.GetParameterArray();
43 |
44 |
45 | //将匿名对象转成SqlParameter
46 | var par3 = SqlSugarTool.GetParameters(new { id = 1 });
47 |
48 |
49 | //用于生成多语言的视图
50 | //LanguageHelper.UpdateView()
51 |
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/SqlSugarForCore.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | sqlSugarCore
5 | 3.5.3.4
6 | sunkaixuan
7 | Landa
8 | http://www.apache.org/licenses/LICENSE-2.0.html
9 | https://github.com/sunkaixuan/ASP_NET_CORE_ORM_SqlSugar
10 | https://secure.gravatar.com/avatar/a82c03402497b2e58fd65038a3699b30
11 | false
12 | Asp.net Core ORM SqlSugar ORM,core 1.0,High-performance, lightweight http://www.cnblogs.com/sunkaixuan/p/5654695.html
13 | Copyright 2016
14 | Asp.net core orm
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/SqlPageModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //设置分页模式
13 | public class SqlPageModel : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动SqlPageModel.Init");
19 | using (var db = SugarDao.GetInstance())
20 | {
21 | try
22 | {
23 | db.PageModel = PageModel.Offset; //启用Sql2012的方式进行分页(默认:RowNumber)
24 |
25 | var list = db.Queryable().OrderBy("id").Skip(0).Take(2).ToList();
26 | var list1 = db.Sqlable().From("t").SelectToPageList("*", "id", 1, 2);
27 |
28 |
29 | List dataPageList = db.Sqlable()
30 | .From("school", "s")
31 | .Join("student", "st", "st.id", "s.id", JoinType.Inner)
32 | .Join("student", "st2", "st2.id", "st.id", JoinType.Left)
33 | .Where("s.id>100 and s.id<100")
34 | .SelectToPageList("st.*", "s.id", 1, 10);
35 |
36 | db.PageModel = PageModel.RowNumber;
37 | var list2 = db.Queryable().OrderBy("id").Skip(0).Take(2).ToList();
38 | var list22 = db.Sqlable().From("t").SelectToPageList("*", "id", 1, 2);
39 | }
40 | catch (Exception ex)
41 | {
42 |
43 | throw new Exception("该Demo要求SqlSever版本为2012及以上版本,错误信息:"+ex.Message);
44 | }
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/PubModel/PubEnum.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | ///
9 | /// join类型
10 | ///
11 | public enum JoinType
12 | {
13 | ///
14 | /// 等值连接
15 | ///
16 | Inner = 0,
17 | ///
18 | /// 左外连
19 | ///
20 | Left = 1,
21 | ///
22 | /// 右外连
23 | ///
24 | Right = 2
25 | }
26 | ///
27 | /// Apply类型
28 | ///
29 | public enum ApplyType
30 | {
31 | ///
32 | /// 笛卡尔积
33 | ///
34 | Cross = 1,
35 | ///
36 | /// 外连
37 | ///
38 | Outer = 2
39 | }
40 | ///
41 | /// 排序类型
42 | ///
43 | public enum OrderByType
44 | {
45 | ///
46 | /// 升序
47 | ///
48 | Asc = 0,
49 | ///
50 | /// 降序
51 | ///
52 | Desc = 1
53 | }
54 | ///
55 | /// 分页类型
56 | ///
57 | public enum PageModel
58 | {
59 | ///
60 | /// 05分页
61 | ///
62 | RowNumber = 0,
63 | ///
64 | /// 12分页
65 | ///
66 | Offset = 1
67 | }
68 | ///
69 | /// 解析类型
70 | ///
71 | public enum ResolveExpressType
72 | {
73 | ///
74 | /// 单个T
75 | ///
76 | OneT = 0,
77 | ///
78 | /// 多个T
79 | ///
80 | NT = 1,
81 |
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Core/ResolveExpress/Models.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | //局部类:解析用到的实体
9 | internal partial class ResolveExpress
10 | {
11 | ///
12 | /// 拉姆达成员类型
13 | ///
14 | public enum MemberType
15 | {
16 | None = 0,
17 | Key = 1,
18 | Value = 2
19 | }
20 | ///
21 | /// 用来处理bool类型的实体
22 | ///
23 | public class ExpressBoolModel
24 | {
25 | ///
26 | /// 唯一标识
27 | ///
28 | public Guid Key { get; set; }
29 | ///
30 | /// 数据类型
31 | ///
32 | public Type Type { get; set; }
33 | ///
34 | /// 原始值
35 | ///
36 | public string OldValue { get; set; }
37 | ///
38 | /// 处事后的值
39 | ///
40 | public string NewValue
41 | {
42 | get
43 | {
44 | if (Type == SqlSugarTool.BoolType)
45 | {
46 | return Convert.ToBoolean(OldValue) ? "1" : "0";
47 | }
48 | else
49 | {
50 | return OldValue.ToString();
51 | }
52 | }
53 | }
54 | ///
55 | /// 处理后的运算对象
56 | ///
57 | public string ConditionalValue
58 | {
59 | get
60 | {
61 | return Convert.ToBoolean(OldValue) ? "(1=1)" : "(1=2)";
62 | }
63 | }
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Log.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //日志记录功能
13 | public class Log : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动Log.Init");
19 | using (var db = SugarDemoDao.GetInstance())
20 | {
21 |
22 | var a1 = db.Queryable().Where(it => it.id == 1).ToList();
23 | var a2 = db.Queryable().OrderBy(it => it.id).ToList();
24 | }
25 | }
26 |
27 | public class SugarConfigs
28 | {
29 | public static Action LogEventStarting = (sql, pars) =>
30 | {
31 | Console.WriteLine("starting:" + sql + " " + pars);
32 |
33 | using (var db = SugarDemoDao.GetInstance())
34 | {
35 | //日志记录件事件里面用到数据库操作 IsEnableLogEvent一定要为false否则将引起死循环,并且要新开一个数据实例 像我这样写就没问题。
36 | db.IsEnableLogEvent = false;
37 | db.ExecuteCommand("select 1");
38 | }
39 | };
40 | public static Action LogEventCompleted = (sql, pars) =>
41 | {
42 | Console.WriteLine("completed:" + sql + " " + pars);
43 | };
44 | }
45 |
46 | ///
47 | /// SqlSugar
48 | ///
49 | public class SugarDemoDao
50 | {
51 |
52 | public static SqlSugarClient GetInstance()
53 | {
54 | var db = new SqlSugarClient(SugarDao.ConnectionString);
55 | db.IsEnableLogEvent = true;//启用日志事件
56 | db.LogEventStarting = SugarConfigs.LogEventStarting;
57 | db.LogEventCompleted = SugarConfigs.LogEventCompleted;
58 | return db;
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/EnumDemo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //枚举的支持
13 | public class EnumDemo:IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动EnumDemo.Init");
19 | using (SqlSugarClient db = SugarDao.GetInstance())
20 | {
21 | var stuList = db.Queryable().ToList();
22 | db.Insert(new Student() { sch_id = SchoolEnum.北大青鸟 });
23 | db.Update(new Student() { sch_id = SchoolEnum.it清华, id = 11 });
24 | var stuList2 = db.Queryable().Where(it => it.sch_id == SchoolEnum.全智).ToList();
25 | }
26 | }
27 | public class Student
28 | {
29 |
30 | ///
31 | /// 说明:-
32 | /// 默认:-
33 | /// 可空:False
34 | ///
35 | public int id { get; set; }
36 |
37 | ///
38 | /// 说明:-
39 | /// 默认:-
40 | /// 可空:True
41 | ///
42 | public string name { get; set; }
43 |
44 | ///
45 | /// 说明:-
46 | /// 默认:-
47 | /// 可空:False
48 | ///
49 | public SchoolEnum sch_id { get; set; }
50 |
51 | ///
52 | /// 说明:-
53 | /// 默认:-
54 | /// 可空:True
55 | ///
56 | public string sex { get; set; }
57 |
58 | ///
59 | /// 说明:-
60 | /// 默认:-
61 | /// 可空:False
62 | ///
63 | public bool isOk { get; set; }
64 |
65 | }
66 |
67 | public enum SchoolEnum
68 | {
69 | 北大青鸟 = 1,
70 | it清华 = 2,
71 | 全智 = 3
72 | }
73 | }
74 |
75 |
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/IgnoreErrorColumns.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //排除错误列
13 | public class IgnoreErrorColumns : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动IgnoreErrorColumns.Init");
19 | using (var db = SugarDao.GetInstance())
20 | {
21 | db.IsIgnoreErrorColumns = true;
22 |
23 | //Student表并没有 AreaName
24 | var id= db.Insert(new STUDENT() { name = "张三", AreaName = "北大" });
25 |
26 |
27 | db.Update(new STUDENT() { id=id.ObjToInt() ,name = "张三2", AreaName = "北大" });
28 | }
29 | }
30 | public class STUDENT {
31 | ///
32 | /// Desc:-
33 | /// Default:-
34 | /// Nullable:False
35 | ///
36 | public int id { get; set; }
37 |
38 | ///
39 | /// Desc:-
40 | /// Default:-
41 | /// Nullable:True
42 | ///
43 | public string name { get; set; }
44 |
45 | ///
46 | /// Desc:学校ID
47 | /// Default:-
48 | /// Nullable:True
49 | ///
50 | public int? sch_id { get; set; }
51 |
52 | ///
53 | /// Desc:-
54 | /// Default:-
55 | /// Nullable:True
56 | ///
57 | public string sex { get; set; }
58 |
59 | ///
60 | /// Desc:-
61 | /// Default:-
62 | /// Nullable:True
63 | ///
64 | public Boolean? isOk { get; set; }
65 |
66 | public string SchoolName { get; set; }
67 |
68 | public string AreaName { get; set; }
69 |
70 | public string SubjectName { get; set; }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/SqlSugarCore/SqlSugarCore.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25420.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{29853D32-F332-48E7-ACBA-4240680D2A6E}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9400E011-5362-4EB3-9711-7DDF11EB5EA1}"
9 | ProjectSection(SolutionItems) = preProject
10 | global.json = global.json
11 | EndProjectSection
12 | EndProject
13 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "SqlSugarTest", "src\SqlSugarCore\SqlSugarTest.xproj", "{C0888E57-6465-476E-AE60-5D5834F5EC11}"
14 | EndProject
15 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "SqlSugarForCore", "src\SqlSugarForCore\SqlSugarForCore.xproj", "{2EA1A286-E605-4EB8-BA44-C5861E8E552A}"
16 | EndProject
17 | Global
18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
19 | Debug|Any CPU = Debug|Any CPU
20 | Release|Any CPU = Release|Any CPU
21 | EndGlobalSection
22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
23 | {C0888E57-6465-476E-AE60-5D5834F5EC11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
24 | {C0888E57-6465-476E-AE60-5D5834F5EC11}.Debug|Any CPU.Build.0 = Debug|Any CPU
25 | {C0888E57-6465-476E-AE60-5D5834F5EC11}.Release|Any CPU.ActiveCfg = Release|Any CPU
26 | {C0888E57-6465-476E-AE60-5D5834F5EC11}.Release|Any CPU.Build.0 = Release|Any CPU
27 | {2EA1A286-E605-4EB8-BA44-C5861E8E552A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
28 | {2EA1A286-E605-4EB8-BA44-C5861E8E552A}.Debug|Any CPU.Build.0 = Debug|Any CPU
29 | {2EA1A286-E605-4EB8-BA44-C5861E8E552A}.Release|Any CPU.ActiveCfg = Release|Any CPU
30 | {2EA1A286-E605-4EB8-BA44-C5861E8E552A}.Release|Any CPU.Build.0 = Release|Any CPU
31 | EndGlobalSection
32 | GlobalSection(SolutionProperties) = preSolution
33 | HideSolutionNode = FALSE
34 | EndGlobalSection
35 | GlobalSection(NestedProjects) = preSolution
36 | {C0888E57-6465-476E-AE60-5D5834F5EC11} = {29853D32-F332-48E7-ACBA-4240680D2A6E}
37 | {2EA1A286-E605-4EB8-BA44-C5861E8E552A} = {29853D32-F332-48E7-ACBA-4240680D2A6E}
38 | EndGlobalSection
39 | EndGlobal
40 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/MappingColumns.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using System.Data.SqlClient;
7 | using SqlSugar;
8 | namespace NewTest.Demos
9 | {
10 | //别名列的功能
11 | public class MappingColumns : IDemos
12 | {
13 |
14 | public void Init()
15 | {
16 | Console.WriteLine("启动MappingColumns.Init");
17 |
18 | //全局设置
19 | using (var db = SugarFactory.GetInstance())
20 | {
21 | var list = db.Queryable().Where(it=>it.classId==1).ToList();
22 | }
23 | }
24 |
25 | public class Student
26 | {
27 |
28 | //id
29 | public int classId { get; set; }
30 |
31 | //name
32 | public string className { get; set; }
33 |
34 | //sch_id
35 | public int classSchoolId { get; set; }
36 |
37 | public int isOk { get; set; }
38 | }
39 |
40 | ///
41 | /// 全局配置别名列(不区分表)
42 | ///
43 | public class SugarConfigs
44 | {
45 | //key实体字段名 value表字段名 ,KEY唯一否则异常
46 | public static List MpList = new List(){
47 | new KeyValue(){ Key="classId", Value="id"},
48 | new KeyValue(){ Key="className", Value="name"},
49 | new KeyValue(){ Key="classSchoolId", Value="sch_id"}
50 | };
51 | }
52 |
53 | ///
54 | /// SqlSugar实例工厂
55 | ///
56 | public class SugarFactory
57 | {
58 |
59 | //禁止实例化
60 | private SugarFactory()
61 | {
62 |
63 | }
64 | public static SqlSugarClient GetInstance()
65 | {
66 | string connection = SugarDao.ConnectionString; //这里可以动态根据cookies或session实现多库切换
67 | var db = new SqlSugarClient(connection);
68 | //注意:只有启动属性映射才可以使用SetMappingColumns
69 | db.IsEnableAttributeMapping = true;
70 | db.SetMappingColumns(SugarConfigs.MpList);//设置关联列 (引用地址赋值,每次赋值都只是存储一个内存地址)
71 | return db;
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Base/TypeExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Reflection;
6 | namespace SqlSugar
7 | {
8 | internal static class TypeExtensions
9 | {
10 |
11 | public static Type[] GetGenericArguments(this Type type)
12 | {
13 | var reval = type.GetTypeInfo().GetGenericArguments();
14 | return reval;
15 | }
16 | public static bool IsGenericType(this Type type)
17 | {
18 | var reval = type.GetTypeInfo().IsGenericType;
19 | return reval;
20 | }
21 | public static PropertyInfo[] GetProperties(this Type type)
22 | {
23 | var reval = type.GetTypeInfo().GetProperties();
24 | return reval;
25 | }
26 | public static PropertyInfo GetProperty(this Type type, string name)
27 | {
28 | var reval = type.GetTypeInfo().GetProperty(name);
29 | return reval;
30 | }
31 |
32 | public static FieldInfo GetField(this Type type, string name)
33 | {
34 | var reval = type.GetTypeInfo().GetField(name);
35 | return reval;
36 | }
37 |
38 | public static bool IsEnum(this Type type)
39 | {
40 | var reval = type.GetTypeInfo().IsEnum;
41 | return reval;
42 | }
43 |
44 | public static MethodInfo GetMethod(this Type type, string name)
45 | {
46 | var reval = type.GetTypeInfo().GetMethod(name);
47 | return reval;
48 | }
49 | public static MethodInfo GetMethod(this Type type, string name, Type[] types)
50 | {
51 | var reval = type.GetTypeInfo().GetMethod(name, types);
52 | return reval;
53 | }
54 | public static ConstructorInfo GetConstructor(this Type type, Type[] types)
55 | {
56 | var reval = type.GetTypeInfo().GetConstructor(types);
57 | return reval;
58 | }
59 |
60 | public static bool IsValueType(this Type type)
61 | {
62 | return type.GetTypeInfo().IsValueType;
63 | }
64 |
65 |
66 | public static bool IsClass(this Type type)
67 | {
68 | return type.GetTypeInfo().IsClass;
69 | }
70 |
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/MappingTable.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 | namespace NewTest.Demos
10 | {
11 | //别名表的功能
12 | public class MappingTable : IDemos
13 | {
14 |
15 | public void Init()
16 | {
17 | Console.WriteLine("启动MappingTable.Init");
18 |
19 | //单个设置
20 | using (var db = SugarDao.GetInstance())
21 | {
22 | var list = db.Queryable("Student").ToList();//查询的是 select * from student 而我的实体名称为V_Student
23 | }
24 |
25 |
26 | //全局设置
27 | using (var db = SugarFactory.GetInstance())
28 | {
29 | var list = db.Queryable().ToList();//查询的是 select * from student 而我的实体名称为V_Student
30 | }
31 | }
32 |
33 |
34 | ///
35 | /// 全局配置类
36 | ///
37 | public class SugarConfigs
38 | {
39 | //key类名 value表名
40 | public static List MpList = new List(){
41 | new KeyValue(){ Key="FormAttr", Value="Flow_FormAttr"},
42 | new KeyValue(){ Key="Student3", Value="Student"},
43 | new KeyValue(){ Key="V_Student", Value="Student"}
44 | };
45 | }
46 |
47 | ///
48 | /// SqlSugar实例工厂
49 | ///
50 | public class SugarFactory
51 | {
52 |
53 | //禁止实例化
54 | private SugarFactory()
55 | {
56 |
57 | }
58 | public static SqlSugarClient GetInstance()
59 | {
60 | string connection = SugarDao.ConnectionString; //这里可以动态根据cookies或session实现多库切换
61 | var db = new SqlSugarClient(connection);
62 |
63 | db.SetMappingTables(SugarConfigs.MpList);//设置关联表 (引用地址赋值,每次赋值都只是存储一个内存地址)
64 |
65 |
66 |
67 | //批量设置别名表
68 | //db.ClassGenerating.ForeachTables(db, tableName =>
69 | //{
70 | // db.AddMappingTable(new KeyValue() { Key = tableName.Replace("bbs.",""), Value = tableName }); //key实体名,value表名
71 | //});
72 |
73 |
74 | return db;
75 | }
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/SerialNumber.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //流水号的功能
13 | public class SerialNumber : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动SerialNumber.Init");
19 | using (SqlSugarClient db = SugarFactory.GetInstance())//开启数据库连接
20 | {
21 | var dientityValue = db.Insert(new Student() { });
22 | var name = db.Queryable().Single(it => it.id == dientityValue.ObjToInt()).name;
23 | Console.WriteLine(name);
24 |
25 | var dientityValue2 = db.Insert(new School() { });
26 | var name2 = db.Queryable().Single(it => it.id == dientityValue2.ObjToInt()).name;
27 | Console.WriteLine(name2); ;
28 | }
29 | }
30 |
31 | ///
32 | /// 全局配置类
33 | ///
34 | public class SugarConfigs
35 | {
36 | public static List NumList = new List(){
37 | new PubModel.SerialNumber(){TableName="Student", FieldName="name", GetNumFunc=()=>{ //GetNumFunc在没有事中使用
38 | return "stud-"+DateTime.Now.ToString("yyyy-MM-dd");
39 | }},
40 | new PubModel.SerialNumber(){TableName="School", FieldName="name", GetNumFuncWithDb=db=>{ //事务中请使用GetNumFuncWithDb保证同一个DB对象,不然会出现死锁
41 | return "ch-"+DateTime.Now.ToString("syyyy-MM-dd");
42 | }}
43 | };
44 | }
45 |
46 | ///
47 | /// SqlSugar实例工厂
48 | ///
49 | public class SugarFactory
50 | {
51 |
52 | //禁止实例化
53 | private SugarFactory()
54 | {
55 |
56 | }
57 | public static SqlSugarClient GetInstance()
58 | {
59 | string connection = SugarDao.ConnectionString; //这里可以动态根据cookies或session实现多库切换
60 | var db = new SqlSugarClient(connection);
61 | db.SetSerialNumber(SugarConfigs.NumList);//设置流水号
62 | return db;
63 | }
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Insert.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 | namespace NewTest.Demos
10 | {
11 | //插入
12 | public class Insert : IDemos
13 | {
14 |
15 | public void Init()
16 | {
17 | Console.WriteLine("启动Inset.Init");
18 | using (var db = SugarDao.GetInstance())
19 | {
20 |
21 | db.Insert(GetInsertItem()); //插入一条记录 (有主键也好,没主键也好,有自增列也好都可以插进去)
22 |
23 |
24 | db.InsertRange(GetInsertList()); //批量插入 支持(别名表等功能)
25 |
26 |
27 | db.SqlBulkCopy(GetInsertList()); //批量插入 适合海量数据插入
28 |
29 |
30 |
31 | //设置不插入列
32 | db.DisableInsertColumns = new string[] { "sex" };//sex列将不会插入值
33 | Student s = new Student()
34 | {
35 | name = "张" + new Random().Next(1, int.MaxValue),
36 | sex = "gril"
37 | };
38 |
39 | var id = db.Insert(s); //插入
40 |
41 | //查询刚插入的sex是否有值
42 | var sex = db.Queryable().Single(it => it.id == id.ObjToInt()).sex;//无值
43 | var name = db.Queryable().Single(it => it.id == id.ObjToInt()).name;//有值
44 |
45 |
46 | //SqlBulkCopy同样支持不挺入列设置
47 | db.SqlBulkCopy(GetInsertList());
48 | }
49 | }
50 |
51 | private static List GetInsertList()
52 | {
53 | List list = new List()
54 | {
55 | new Student()
56 | {
57 | name="张"+new Random().Next(1,int.MaxValue),
58 | isOk=true,
59 | sch_id=1
60 | },
61 | new Student()
62 | {
63 | name="张"+new Random().Next(1,int.MaxValue),
64 | isOk=false,
65 | sch_id=2
66 | }
67 | };
68 | return list;
69 | }
70 |
71 | private static Student GetInsertItem()
72 | {
73 | Student s = new Student()
74 | {
75 | name = "张" + new Random().Next(1, int.MaxValue)
76 | };
77 | return s;
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Generating/ClassTemplate.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 |
9 | ///
10 | /// 生成实体格式模版
11 | ///
12 | public class ClassTemplate
13 | {
14 | ///
15 | ///替换模版
16 | ///
17 | ///
18 | ///
19 | ///
20 | ///
21 | ///
22 | ///
23 | internal static string Replace(string templateStr, string nameSpaceStr, string foreachStr, string classNameStr, List primaryKeyName = null)
24 | {
25 | if (nameSpaceStr.IsNullOrEmpty())
26 | {
27 | nameSpaceStr = "System";
28 | }
29 | templateStr = templateStr.Replace("$foreach", foreachStr)
30 | .Replace("$namespace", nameSpaceStr)
31 | .Replace("$className", classNameStr);
32 | //处理主键
33 | if (primaryKeyName != null && primaryKeyName.Count > 0)
34 | {
35 | templateStr = templateStr.Replace("$primaryKeyName", primaryKeyName[0]);
36 | //处理特殊的主键取值
37 | for (int i = 0; i < primaryKeyName.Count; i++)
38 | {
39 | templateStr = templateStr.Replace("$primaryKeyName_" + i + "", primaryKeyName[i]);
40 | }
41 | }
42 | return templateStr;
43 | }
44 |
45 | ///
46 | /// 字段模版
47 | ///
48 | public static string ItemTemplate = " public {0}{3} {1} {2}";
49 |
50 | ///
51 | /// 生成的实体类模版
52 | ///
53 | public static string Template =
54 | @"using System;
55 | using System.Linq;
56 | using System.Text;
57 |
58 | namespace $namespace
59 | {
60 | public class $className
61 | {
62 | $foreach
63 | }
64 | }
65 | ";
66 | ///
67 | /// 生成实体类字段摘要模版
68 | ///
69 | public static string ClassFieldSummaryTemplate = @" ///
70 | /// Desc:{0}
71 | /// Default:{1}
72 | /// Nullable:{2}
73 | ///
74 | ";
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Filter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //过滤器用法
13 | //使用场合(例如:假删除查询,这个时候就可以设置一个过滤器,不需要每次都 .Where(it=>it.IsDelete==true))
14 | public class Filter : IDemos
15 | {
16 |
17 | public void Init()
18 | {
19 | Console.WriteLine("启动Filter.Init");
20 | using (SqlSugarClient db = SugarDaoFilter.GetInstance())//开启数据库连接
21 | {
22 | //设置走哪个过滤器
23 | db.CurrentFilterKey = "role,role2"; //支持多个过滤器以逗号隔开
24 |
25 | //queryable
26 | var list = db.Queryable().ToList(); //通过全局过滤器对需要权限验证的数据进行过滤
27 | //相当于db.Queryable().Where("id=@id",new{id=1})
28 |
29 |
30 | //sqlable
31 | var list2 = db.Sqlable().From("s").SelectToList("*");
32 | //同上
33 |
34 | //sqlQuery
35 | var list3 = db.SqlQuery("select * from Student WHERE 1=1");
36 | //同上
37 | }
38 | }
39 | ///
40 | /// 扩展SqlSugarClient
41 | ///
42 | public class SugarDaoFilter
43 | {
44 | //禁止实例化
45 | private SugarDaoFilter()
46 | {
47 |
48 | }
49 | ///
50 | /// 页面所需要的过滤函数
51 | ///
52 | private static Dictionary> _filterParas = new Dictionary>()
53 | {
54 | { "role",()=>{
55 | return new KeyValueObj(){ Key=" id=@id" , Value=new{ id=1}};
56 | }
57 | },
58 | { "role2",()=>{
59 | return new KeyValueObj(){ Key=" id>0"};
60 | }
61 | },
62 | };
63 | public static SqlSugarClient GetInstance()
64 | {
65 | string connection = SugarDao.ConnectionString; //这里可以动态根据cookies或session实现多库切换
66 | var db = new SqlSugarClient(connection);
67 | db.SetFilterItems(_filterParas);
68 |
69 | db.IsEnableLogEvent = true;//启用日志事件
70 | db.LogEventStarting = (sql, par) => { Console.WriteLine(sql + " " + par + "\r\n"); };
71 | return db;
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Filter2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //行过滤加列过滤
13 | //权限管理的最佳设计
14 | public class Filter2 : IDemos
15 | {
16 |
17 | public void Init()
18 | {
19 | Console.WriteLine("启动Filter2.Init");
20 | using (SqlSugarClient db = SugarDaoFilter.GetInstance())//开启数据库连接
21 | {
22 | //设置走哪个过滤器
23 | db.CurrentFilterKey = "role1";
24 | //queryable
25 | var list = db.Queryable().ToJson(); //where id=1 , 可以查看id和name
26 |
27 |
28 | //设置走哪个过滤器
29 | db.CurrentFilterKey = "role2";
30 | //queryable
31 | var list2 = db.Queryable().ToJson(); //where id=2 , 可以查看name
32 |
33 | }
34 | }
35 | ///
36 | /// 扩展SqlSugarClient
37 | ///
38 | public class SugarDaoFilter
39 | {
40 | //禁止实例化
41 | private SugarDaoFilter()
42 | {
43 |
44 | }
45 | ///
46 | /// 页面所需要的过滤行
47 | ///
48 | private static Dictionary> _filterRos = new Dictionary>()
49 | {
50 | { "role1",()=>{
51 | return new KeyValueObj(){ Key=" id=@id" , Value=new{ id=1}};
52 | }
53 | },
54 | { "role2",()=>{
55 | return new KeyValueObj() { Key = " id=@id", Value = new { id = 2 } };
56 | }
57 | },
58 | };
59 | ///
60 | /// 页面所需要的过滤列
61 | ///
62 | private static Dictionary> _filterColumns = new Dictionary>()
63 | {
64 | { "role1",new List(){"id","name"}
65 | },
66 | { "role2",new List(){"name"}
67 | },
68 | };
69 | public static SqlSugarClient GetInstance()
70 | {
71 | string connection = SugarDao.ConnectionString; //这里可以动态根据cookies或session实现多库切换
72 | var db = new SqlSugarClient(connection);
73 |
74 | //支持sqlable和queryable
75 | db.SetFilterItems(_filterRos);
76 |
77 | //列过滤只支持queryable
78 | db.SetFilterItems(_filterColumns);
79 |
80 |
81 | db.IsEnableLogEvent = true;//启用日志事件
82 | db.LogEventStarting = (sql, par) => { Console.WriteLine(sql + " " + par + "\r\n"); };
83 | return db;
84 | }
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Tool/JsonConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Data;
5 | using System.Linq;
6 | using System.Collections;
7 | using System.Text.RegularExpressions;
8 | using Newtonsoft.Json;
9 |
10 | namespace SqlSugar
11 | {
12 | ///
13 | /// 作者:sunkaixaun
14 | ///
15 | public class JsonConverter
16 | {
17 | ///
18 | /// dataTable转成JSON
19 | /// add sunkaixuan
20 | ///
21 | ///
22 | ///
23 | public static string DataTableToJson(DataTable table)
24 | {
25 | List> parentRow = new List>();
26 | foreach (DataRow row in table.Rows)
27 | {
28 | Dictionary childRow = new Dictionary();
29 | foreach (DataColumn col in table.Columns)
30 | {
31 | var columnValue = row[col.ColumnName];
32 | if (columnValue == DBNull.Value)
33 | {
34 | columnValue = null;
35 | }
36 | childRow.Add(col.ColumnName, columnValue);
37 | }
38 | parentRow.Add(childRow);
39 | }
40 | return JsonConvert.SerializeObject(parentRow);
41 | }
42 | ///
43 | /// DataTable转成Json字符串
44 | ///
45 | ///
46 | ///
47 | ///
48 | public static string DataTableToJson(DataTable table, string dateFormat)
49 | {
50 | var reval = DataTableToJson(table);
51 | if (dateFormat.IsNullOrEmpty()) return reval;
52 | reval = Regex.Replace(reval, @"\\/Date\((\d+)\)\\/", match =>
53 | {
54 | DateTime dt = new DateTime(1970, 1, 1);
55 | dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
56 | dt = dt.ToLocalTime();
57 | return dt.ToString(dateFormat);
58 | });
59 | return reval;
60 | }
61 |
62 |
63 | ///
64 | /// json转换object动态类
65 | /// add duk by 2016-05-19
66 | ///
67 | ///
68 | ///
69 | public static dynamic ConvertJson(string json)
70 | {
71 | var dy = JsonConvert.DeserializeObject(json);
72 | return dy;
73 | }
74 |
75 | ///
76 | /// 将对象序列化成字符串
77 | ///
78 | ///
79 | ///
80 | public static string Serialize(object o)
81 | {
82 | return JsonConvert.SerializeObject(o);
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/CreateClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | //生成实体函数
13 | public class CreateClass : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动CreateClass.Init");
19 | using (var db = SugarDao.GetInstance())
20 | {
21 | //可以结合别名表,请看别名表的用法
22 | //db.SetMappingTables(mappingTableList);
23 |
24 | db.ClassGenerating.CreateClassFiles(db, ("e:/TestModels"), "Models");
25 |
26 |
27 | //批量设置别名表,可以方便生成指定格式的实体对象
28 | db.ClassGenerating.ForeachTables(db, tableName =>
29 | {
30 | db.AddMappingTable(new KeyValue() { Key = "Rename_"+tableName, Value = tableName });
31 | });
32 |
33 | //生成的文件都Rename_开头
34 | db.ClassGenerating.CreateClassFiles(db, ("e:/TestModels"), "Models",
35 | null,
36 | className => {
37 | //生成文件之后的回调
38 | }, tableName => {
39 | //生成文件之前的回调
40 | });
41 |
42 |
43 | //只生成student和school表的实体
44 | db.ClassGenerating.CreateClassFilesByTableNames(db, "e:/TestModels2", "Models", new string[] { "student", "school" });
45 |
46 | //根据表名生成class字符串
47 | var str = db.ClassGenerating.TableNameToClass(db, "Student");
48 |
49 | var dynamicToClassStr = db.ClassGenerating.DynamicToClass(new { id = 1 }, "dyName");
50 |
51 | //根据SQL语句生成class字符串
52 | var str2 = db.ClassGenerating.SqlToClass(db, "select top 1 * from Student", "student");
53 |
54 | //改变值(lassTemplate.ItemTemplate=XXXX)可以自定义格式
55 | var tempItem = ClassTemplate.ItemTemplate;//例如可以在生成的实体添加默认构造函数给指定的字段赋默认值或者公司信息等
56 | var temp = ClassTemplate.Template;
57 | var temSummary = ClassTemplate.ClassFieldSummaryTemplate;
58 |
59 |
60 | //设置新格式模板
61 | //主键Guid.New(),
62 | //CreateTime为DateTime.Now
63 | //IsRemove=0
64 | //UpdateTime为DateTime.Now
65 | ClassTemplate.Template = "using System;\r\nusing System.Linq;\r\nusing System.Text;\r\n\r\nnamespace $namespace\r\n{\r\n public class $className\r\n {\r\n public $className() \r\n { \r\n this.CreateTime = DateTime.Now;\r\n this. = 0;\r\n this.UpdateTime=DateTime.Now;\r\n this.$primaryKeyName=Guid.NewGuid().ToString(\"N\").ToUpper();\r\n }\r\n $foreach\r\n }\r\n}\r\n";
66 |
67 | //新格式的实体字符串
68 | var str3 = db.ClassGenerating.TableNameToClass(db, "Student");
69 |
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Tool/SqlException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | ///
9 | /// ** 描述:SqlSugar自定义异常
10 | /// ** 创始时间:2015-7-13
11 | /// ** 修改时间:-
12 | /// ** 作者:sunkaixuan
13 | /// ** 使用说明:
14 | ///
15 | public class SqlSugarException : Exception
16 | {
17 | ///
18 | /// SqlSugar异常
19 | ///
20 | /// 错误信息
21 | public SqlSugarException(string message)
22 | : base(message)
23 | {
24 |
25 | }
26 | ///
27 | /// SqlSugar异常
28 | ///
29 | /// 错误信息
30 | /// ORM生成的SQL
31 | public SqlSugarException(string message, string sql)
32 | : base(GetMessage(message, sql))
33 | {
34 |
35 | }
36 | ///
37 | /// SqlSugar异常
38 | ///
39 | /// 错误信息
40 | /// ORM生成的SQL
41 | /// 错误函数的参数
42 | public SqlSugarException(string message, string sql, object pars)
43 | : base(GetMessage(message, sql, pars))
44 | {
45 |
46 | }
47 | ///
48 | /// SqlSugar异常
49 | ///
50 | /// 错误信息
51 | /// 错误函数的参数
52 | public SqlSugarException(string message,object pars)
53 | : base(GetMessage(message,pars))
54 | {
55 |
56 | }
57 |
58 | private static string GetMessage(string message, object pars)
59 | {
60 | var parsStr = string.Empty; ;
61 | if (pars != null)
62 | {
63 | parsStr = JsonConverter.Serialize(pars);
64 | }
65 | var reval = GetLineMessage("错误信息", message) + GetLineMessage("函数参数", parsStr);
66 | return reval;
67 |
68 | }
69 |
70 |
71 | private static string GetMessage(string message, string sql, object pars)
72 | {
73 | if (pars == null)
74 | {
75 | return GetMessage(message, sql);
76 | }
77 | else
78 | {
79 | var reval = GetLineMessage("错误信息 ", message) + GetLineMessage("ORM生成的Sql", sql) + GetLineMessage("函数参数 ", JsonConverter.Serialize(pars));
80 | return reval;
81 | }
82 | }
83 |
84 |
85 | private static string GetMessage(string message, string sql)
86 | {
87 | var reval = GetLineMessage("错误信息 ", message) + GetLineMessage("ORM生成的Sql", sql);
88 | return reval;
89 | }
90 |
91 | private static string GetLineMessage(string key, string value)
92 | {
93 | return string.Format("{0} : 【{1}】\r\n", key, value);
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using SqlSugar;
6 | using NewTest.Demos;
7 | using System.Text;
8 |
9 | namespace SqlSugarTest
10 | {
11 | public class Program
12 | {
13 | public static void Main(string[] args)
14 | {
15 | Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
16 |
17 | //设置执行的DEMO
18 | string switchOn = "select";
19 | IDemos demo = null;
20 | switch (switchOn)
21 | {
22 | /****************************基本功能**************************************/
23 | //查询
24 | case "select": demo = new Select(); break;
25 | //删除
26 | case "delete": demo = new Delete(); break;
27 | //插入
28 | case "insert": demo = new Insert(); break;
29 | //更新
30 | case "update": demo = new Update(); break;
31 | //基层函数的用法
32 | case "ado": demo = new Ado(); break;
33 | //事务
34 | case "tran": demo = new Tran(); break;
35 | //创建实体函数
36 | case "createclass": demo = new CreateClass(); break;
37 | //T4生成 http://www.cnblogs.com/sunkaixuan/p/5751503.html
38 |
39 | //日志记录
40 | case "log": demo = new Log(); break;
41 | //枚举支持
42 | case "enum": demo = new EnumDemo(); break;
43 |
44 |
45 |
46 | /****************************实体映射**************************************/
47 | //自动排除非数据库列
48 | case "ignoreerrorcolumns": demo = new IgnoreErrorColumns(); break;
49 | //别名表
50 | case "mappingtable": demo = new MappingTable(); break;
51 | //别名列
52 | case "mappingcolumns": demo = new MappingColumns(); break;
53 | //通过属性的方法设置别名表和别名字段
54 | case "attributesmapping": demo = new AttributesMapping(); break;
55 |
56 |
57 |
58 | /****************************业务应用**************************************/
59 | //过滤器
60 | case "filter": demo = new Filter(); break;
61 | //过滤器2
62 | case "filter2": demo = new Filter2(); break;
63 | //流水号功能
64 | case "serialnumber": demo = new SerialNumber(); break;
65 |
66 | //多语言支持 http://www.cnblogs.com/sunkaixuan/p/5709583.html
67 | //多库并行计算 http://www.cnblogs.com/sunkaixuan/p/5046517.html
68 |
69 | //配置与实例的用法
70 | case "initconfig": demo = new InitConfig(); break;
71 |
72 |
73 |
74 | /****************************支持**************************************/
75 | //公开函数数
76 | case "pubmethod": demo = new PubMethod(); break;
77 | //Sql2012分页的支持
78 | case "sqlpagemodel": demo = new SqlPageModel(); break;
79 | //设置ToJson的日期格式
80 | case "serializerdateformat": demo = new SerializerDateFormat(); break;
81 |
82 |
83 |
84 | /****************************测试用例**************************************/
85 | case "test": demo = new Test(); break;
86 |
87 | default: Console.WriteLine("switchOn的值错误,请输入正确的 case"); break;
88 |
89 | }
90 | //执行DEMO
91 | demo.Init();
92 |
93 | //更多例子请查看API
94 | //http://www.cnblogs.com/sunkaixuan/p/5654695.html
95 | Console.WriteLine("执行成功请关闭窗口");
96 | Console.ReadKey();
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/InitConfig.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 |
10 | namespace NewTest.Demos
11 | {
12 | ///
13 | ///如何避免初始化SqlSugarClient时,参数赋值引起的性能的浪费
14 | ///
15 | public class InitConfig : IDemos
16 | {
17 |
18 | public void Init()
19 | {
20 | Console.WriteLine("启动InitConfig.Init");
21 | using (SqlSugarClient db = SugarPocoDao.GetInstance())//开启数据库连接
22 | {
23 |
24 | }
25 | }
26 |
27 | ///
28 | /// SqlSugarClient初始化全配置类
29 | ///
30 | public class DaoInitConfig
31 | {
32 | //别名列
33 | public static List columnMappingList= new List() {
34 | new KeyValue(){ Key="entityId", Value="tableId"},
35 | new KeyValue(){ Key="entityName", Value="tableName"}
36 | };
37 |
38 | //别名表
39 | public static List tableMappingList = null;
40 |
41 |
42 | //流水号
43 | public static List serialNumber = new List(){
44 | new PubModel.SerialNumber(){TableName="Student", FieldName="name", GetNumFunc=()=>{ return "stud-"+DateTime.Now.ToString("yyyy-MM-dd");}},
45 | new PubModel.SerialNumber(){TableName="School", FieldName="name", GetNumFuncWithDb=db=>{ return "ch-"+DateTime.Now.ToString("syyyy-MM-dd"); }}
46 | };
47 |
48 | //自动排除非数据库列
49 | public static bool IsIgnoreErrorColumns=true;
50 |
51 | }
52 |
53 |
54 | ///
55 | /// 扩展SqlSugarClient
56 | ///
57 | public class SugarPocoDao
58 | {
59 | //禁止实例化
60 | private SugarPocoDao()
61 | {
62 |
63 | }
64 |
65 | public static SqlSugarClient GetInstance()
66 | {
67 |
68 | string connection = SugarDao.ConnectionString; //这里可以动态根据cookies或session实现多库切换
69 | var db = new SqlSugarClient(connection);
70 |
71 | /**这种写法只给db对象添加了4个指向地址(DaoInitConfig变量都为静态对象),并非指向内容,指向内容初始化后存储在内存当中,所以性能就不用说了 **/
72 |
73 | db.SetMappingTables(GetMappingTables(db));//设置别名表
74 |
75 | db.SetMappingColumns(DaoInitConfig.columnMappingList);//设置别名列
76 |
77 | db.SetSerialNumber(DaoInitConfig.serialNumber);//设置流水号
78 |
79 | db.IsIgnoreErrorColumns = DaoInitConfig.IsIgnoreErrorColumns; //自动排除非数据库列
80 |
81 |
82 | return db;
83 | }
84 |
85 | ///
86 | /// 批量设置别名表
87 | ///
88 | ///
89 | ///
90 | private static List GetMappingTables(SqlSugarClient db)
91 | {
92 | if (DaoInitConfig.tableMappingList == null)
93 | {
94 | DaoInitConfig.tableMappingList = new List();
95 | db.ClassGenerating.ForeachTables(db, name =>//内置遍历表名和视图名函数
96 | {
97 | //给所有表名加dbo.
98 | DaoInitConfig.tableMappingList.Add(new KeyValue() { Key = name, Value ="dbo."+name });
99 |
100 | //动态获取sechma
101 | // DaoInitConfig.tableMappingList.Add(new KeyValue() { Key = name, Value = db.ClassGenerating.GetTableNameWithSchema(db,name) });
102 | });
103 | }
104 | return DaoInitConfig.tableMappingList;
105 | }
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/AttributesMapping.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 | using SqlSugar;
9 | namespace NewTest.Demos
10 | {
11 | //通过属性的方法设置别名表和别名字段(主键和自添列都无需设置 SQLSUGAR会帮你自动处理)
12 | //注意:【属性映射和 (SetMappingTables、SetMappingColumns)方式映射 2种选其中一,不清楚底层缓存机质不建议同时使用】
13 | public class AttributesMapping : IDemos
14 | {
15 |
16 | public void Init()
17 | {
18 | Console.WriteLine("启动AttributesMapping.Init");
19 | using (var db = DBManager.GetInstance())
20 | {
21 |
22 | //查询
23 | var list = db.Queryable()
24 | .Where(it => it.className.Contains("小")).OrderBy(it => it.classSchoolId).Select(it => new V_Student() { id = it.classId, name = it.className }).ToList();
25 | var list2 = db.Queryable()
26 | .JoinTable((s1, s2) => s1.classSchoolId == s2.classId)
27 | .OrderBy((s1, s2) => s1.classId)
28 | .Select((s1, s2) => new V_Student() { id = s1.classId, name = s1.className, SchoolName = s2.className }).ToList();
29 |
30 | //添加
31 | TestStudent s = new TestStudent();
32 | s.className = "属性名";
33 | s.classSchoolId = 1;
34 | var id = db.Insert(s);
35 | s.classId = id.ObjToInt();
36 |
37 |
38 | db.SqlBulkCopy(new List() { s });
39 |
40 |
41 | //更新
42 | db.Update(s);
43 | db.Update(s, 100);
44 | db.Update(s, it => it.classId == 100);
45 | db.SqlBulkReplace(new List() { s });
46 |
47 | //删除
48 | db.Delete(it => it.classId == 100);
49 |
50 | //根据实体赋值实体一定要有主键,并且要有值。
51 | db.Delete(new TestStudent() { classId = 200 });
52 | }
53 | }
54 |
55 | ///
56 | /// 属性只作为初始化映射,SetMappingTables和SetMappingColumns可以覆盖
57 | ///
58 | [SugarMapping(TableName = "Student")]
59 | public class TestStudent
60 | {
61 |
62 | [SugarMapping(ColumnName = "id")]
63 | public int classId { get; set; }
64 |
65 | [SugarMapping(ColumnName = "name")]
66 | public string className { get; set; }
67 |
68 | [SugarMapping(ColumnName = "sch_id")]
69 | public int classSchoolId { get; set; }
70 |
71 | public int isOk { get; set; }
72 |
73 | ///
74 | /// 数据库并没有这一列
75 | ///
76 | public string errorField { get; set; }
77 | }
78 |
79 |
80 | [SugarMapping(TableName = "School")]
81 | public class TestSchool
82 | {
83 |
84 | [SugarMapping(ColumnName = "id")]
85 | public int classId { get; set; }
86 |
87 | [SugarMapping(ColumnName = "name")]
88 | public string className { get; set; }
89 |
90 | public int AreaId = 1;
91 | }
92 | }
93 |
94 | public class DBManager
95 | {
96 |
97 | public static SqlSugarClient GetInstance()
98 | {
99 | var db = new SqlSugarClient(SugarDao.ConnectionString);
100 | db.IsEnableAttributeMapping = true;//启用属性映射
101 | db.IsIgnoreErrorColumns = true;//忽略非数据库列
102 |
103 |
104 |
105 | db.IsEnableLogEvent = true;//启用日志事件
106 | db.LogEventStarting = (sql, par) => { Console.WriteLine(sql + " " + par + "\r\n"); };
107 |
108 |
109 | return db;
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarCore/Demos/Update.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NewTest.Dao;
6 | using Models;
7 | using System.Data.SqlClient;
8 |
9 | namespace NewTest.Demos
10 | {
11 | //更新
12 | public class Update : IDemos
13 | {
14 |
15 | public void Init()
16 | {
17 | Console.WriteLine("启动Ado.Update");
18 | using (var db = SugarDao.GetInstance())
19 | {
20 |
21 | //指定列更新
22 | db.Update(new { name = "蓝翔14" }, it => it.id == 14); //只更新name列
23 | db.Update(new { name = "蓝翔11 23 12", areaId = 2 }, 11, 23, 12);
24 | db.Update(new { name = "蓝翔2" }, new string[] { "11", "21" });
25 | db.Update(new { name = "蓝翔2" }, it => it.id == 100);
26 | var array=new int[]{1,2,3};
27 | db.Update(new { name = "蓝翔2" }, it => array.Contains(it.id));// id in 1,2,3
28 |
29 |
30 | //支持字典更新,适合动态权限
31 | var dic = new Dictionary();
32 | dic.Add("name", "第十三条");
33 | dic.Add("areaId", "1");
34 | db.Update(dic, 13);
35 |
36 |
37 | //整个实体更新
38 | db.Update(new School { id = 16, name = "蓝翔16", AreaId = 1 });
39 | db.Update(new School { id = 12, name = "蓝翔12", AreaId = 2 }, it => it.id == 18);
40 | db.Update(new School() { id = 11, name = "青鸟11" });
41 |
42 | //设置不更新列
43 | db.DisableUpdateColumns = new string[] { "CreateTime" };//设置CreateTime不更新
44 |
45 | TestUpdateColumns updObj = new TestUpdateColumns()
46 | {
47 | VGUID = Guid.Parse("542b5a27-6984-47c7-a8ee-359e483c8470"),
48 | Name = "xx",
49 | Name2 = "xx2",
50 | IdentityField = 0,
51 | CreateTime = null
52 | };
53 |
54 | //CreateTime将不会被更新
55 | db.Update(updObj);
56 | //以前实现这种更新需要用指定列的方式实现,现在就简单多了。
57 |
58 |
59 |
60 | //批量更新 数据量小时建议使用
61 | var updateResult = db.UpdateRange(GetUpdateList());
62 |
63 | //批量更新 数据量大时建议使用
64 | var updateResult2 = db.SqlBulkReplace(GetUpdateList2());
65 |
66 | }
67 | }
68 |
69 |
70 |
71 | private static List GetUpdateList()
72 | {
73 | List list = new List()
74 | {
75 | new Student()
76 | {
77 | id=1001,
78 | name="1张1001"+new Random().Next(1,int.MaxValue)
79 | },
80 | new Student()
81 | {
82 | id=1002,
83 | name="1张1002"+new Random().Next(1,int.MaxValue)
84 | }
85 | };
86 | return list;
87 | }
88 | private static List GetUpdateList2()
89 | {
90 | List list = new List()
91 | {
92 | new Student()
93 | {
94 | id=1010,
95 | name="小妹"+new Random().Next(1,int.MaxValue),
96 | isOk=false,
97 | sch_id=2,
98 | sex="gril"
99 | },
100 | new Student()
101 | {
102 | id=1011,
103 | name="小子"+new Random().Next(1,int.MaxValue),
104 | isOk=true,
105 | sch_id=3,
106 | sex="boy"
107 | }
108 | };
109 | return list;
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Core/ResolveExpress/ResolveFieldName.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Linq.Expressions;
6 |
7 | namespace SqlSugar
8 | {
9 | //局部类 解析字段名
10 | internal partial class ResolveExpress
11 | {
12 | ///
13 | /// 获取拉姆达表达式的字段值
14 | ///
15 | ///
16 | /// 数据库访问对象
17 | ///
18 | public string GetExpressionRightField(Expression exp, SqlSugarClient db)
19 | {
20 | DB = db;
21 | string reval = "";
22 | LambdaExpression lambda = exp as LambdaExpression;
23 | var isConvet = lambda.Body.NodeType.IsIn(ExpressionType.Convert);
24 | var isMember = lambda.Body.NodeType.IsIn(ExpressionType.MemberAccess);
25 | if (!isConvet && !isMember)
26 | {
27 | throw new SqlSugarException(FileldErrorMessage);
28 | }
29 | try
30 | {
31 | if (isConvet)
32 | {
33 | var memberExpr =((UnaryExpression)lambda.Body).Operand as MemberExpression;
34 | reval= memberExpr.Member.Name;
35 | }
36 | else//isMember
37 | {
38 | reval= (lambda.Body as MemberExpression).Member.Name;
39 | }
40 | }
41 | catch (Exception)
42 | {
43 | throw new SqlSugarException(FileldErrorMessage);
44 | }
45 | if (DB != null && DB.IsEnableAttributeMapping && DB._mappingColumns.IsValuable())
46 | {
47 | if (DB._mappingColumns.Any(it => it.Key == reval))
48 | {
49 | var dbName = DB._mappingColumns.Single(it => it.Key == reval).Value;
50 | return dbName;
51 | }
52 | }
53 | return reval;
54 | }
55 |
56 | ///
57 | /// 获取拉姆达表达式的字段值多个T模式
58 | ///
59 | ///
60 | /// 数据库访问对象
61 | ///
62 | public string GetExpressionRightFieldByNT(Expression exp, SqlSugarClient db)
63 | {
64 | DB = db;
65 | string reval = "";
66 | LambdaExpression lambda = exp as LambdaExpression;
67 | var isConvet = lambda.Body.NodeType.IsIn(ExpressionType.Convert);
68 | var isMember = lambda.Body.NodeType.IsIn(ExpressionType.MemberAccess);
69 | if (!isConvet && !isMember)
70 | {
71 | throw new SqlSugarException(FileldErrorMessage);
72 | }
73 | try
74 | {
75 | if (isConvet)
76 | {
77 | var memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
78 | reval= memberExpr.ToString();
79 | }
80 | else//isMember
81 | {
82 | reval= lambda.Body.ToString();
83 | }
84 | }
85 | catch (Exception)
86 | {
87 | throw new SqlSugarException(FileldErrorMessage);
88 | }
89 | if (DB != null && DB.IsEnableAttributeMapping && DB._mappingColumns.IsValuable())
90 | {
91 | if (DB._mappingColumns.Any(it => reval.EndsWith("."+it.Key)))
92 | {
93 | var preName = reval.Split('.').First();
94 | var dbName = DB._mappingColumns.Single(it => reval.EndsWith("." + it.Key)).Value;
95 | return preName+"."+dbName;
96 | }
97 | }
98 | return reval;
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Generating/SugarAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Reflection;
6 |
7 | namespace SqlSugar
8 | {
9 | ///
10 | /// 表名属性
11 | ///
12 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = true)]
13 | public class SugarMappingAttribute : Attribute
14 | {
15 | private string tableName;
16 | ///
17 | /// 据库对应的表名
18 | ///
19 | public string TableName
20 | {
21 | get { return tableName; }
22 | set { tableName = value; }
23 | }
24 |
25 | private string columnName;
26 | ///
27 | /// 数据库对应的列名
28 | ///
29 | public string ColumnName
30 | {
31 | get { return columnName; }
32 | set { columnName = value; }
33 | }
34 | }
35 |
36 | internal class ReflectionSugarMapping
37 | {
38 | ///
39 | /// 通过反射取自定义属性
40 | ///
41 | ///
42 | public static SugarMappingModel GetMappingInfo()
43 | {
44 | Type objType = typeof(T);
45 | string cacheKey = "ReflectionSugarMapping.DisplaySelfAttribute" + objType.FullName;
46 | var cm = CacheManager.GetInstance();
47 | if (cm.ContainsKey(cacheKey))
48 | {
49 | return cm[cacheKey];
50 | }
51 | else
52 | {
53 | SugarMappingModel reval = new SugarMappingModel();
54 | string tableName = string.Empty;
55 | List columnInfoList = new List();
56 | var oldName = objType.Name;
57 | //取属性上的自定义特性
58 | foreach (PropertyInfo propInfo in objType.GetProperties())
59 | {
60 | object[] objAttrs = propInfo.GetCustomAttributes(typeof(SugarMappingAttribute), true).ToArray();
61 | if (objAttrs.Length > 0)
62 | {
63 | if (objAttrs[0] is SugarMappingAttribute)
64 | {
65 | SugarMappingAttribute attr = objAttrs[0] as SugarMappingAttribute;
66 | if (attr != null)
67 | {
68 | columnInfoList.Add(new KeyValue() { Key = propInfo.Name, Value = attr.ColumnName }); //列名
69 | }
70 | }
71 | }
72 | }
73 |
74 | //取类上的自定义特性
75 | object[] objs = objType.GetTypeInfo().GetCustomAttributes(typeof(SugarMappingAttribute), true).ToArray();
76 | foreach (object obj in objs)
77 | {
78 | if (obj is SugarMappingAttribute)
79 | {
80 | SugarMappingAttribute attr = obj as SugarMappingAttribute;
81 | if (attr != null)
82 | {
83 |
84 | tableName = attr.TableName;//表名只有获取一次
85 | break;
86 | }
87 | }
88 | }
89 | if (string.IsNullOrEmpty(tableName))
90 | {
91 | tableName = objType.Name;
92 | }
93 | reval.TableMaping = new KeyValue() { Key = oldName, Value = tableName };
94 | reval.ColumnsMapping = columnInfoList;
95 | cm.Add(cacheKey,reval,cm.Day);
96 | return reval;
97 | }
98 | }
99 | }
100 |
101 | internal class SugarMappingModel
102 | {
103 |
104 | public KeyValue TableMaping { get; set; }
105 | public List ColumnsMapping { get; set; }
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/PubModel/PubModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | ///
9 | /// ** 描述:公共参数表
10 | /// ** 创始时间:2015-7-20
11 | /// ** 修改时间:-
12 | /// ** 作者:sunkaixuan
13 | /// ** 使用说明:
14 | ///
15 | public class PubModel
16 | {
17 | ///
18 | /// 用于存储数据表与列的映射信息
19 | ///
20 | public class DataTableMap
21 | {
22 | ///
23 | /// 表名
24 | ///
25 | public object TABLE_NAME { get; set; }
26 | ///
27 | /// 表ID
28 | ///
29 | public object TABLE_ID { get; set; }
30 | ///
31 | /// 列名
32 | ///
33 | public object COLUMN_NAME { get; set; }
34 | ///
35 | /// 数据类型
36 | ///
37 | public object DATA_TYPE { get; set; }
38 | ///
39 | /// 字符最大长度
40 | ///
41 | public object CHARACTER_MAXIMUM_LENGTH { get; set; }
42 | ///
43 | /// 备注
44 | ///
45 | public object COLUMN_DESCRIPTION { get; set; }
46 | ///
47 | /// 默认值
48 | ///
49 | public object COLUMN_DEFAULT { get; set; }
50 | ///
51 | /// 是否允许为null
52 | ///
53 | public object IS_NULLABLE { get; set; }
54 | ///
55 | /// 是否是主键
56 | ///
57 | public object IS_PRIMARYKEY { get; set; }
58 | }
59 |
60 | ///
61 | /// 流水号设置实体
62 | ///
63 | public class SerialNumber
64 | {
65 | ///
66 | /// 表名
67 | ///
68 | public string TableName { get; set; }
69 | ///
70 | /// 字段名
71 | ///
72 | public string FieldName { get; set; }
73 | ///
74 | /// 获取流水号函数
75 | ///
76 | public Func GetNumFunc { get; set; }
77 | ///
78 | /// 获取流水号函数(解决事务中死锁BUG)
79 | ///
80 | public Func GetNumFuncWithDb { get; set; }
81 | }
82 |
83 | ///
84 | /// 多语言设置的参数表
85 | ///
86 | public class Language
87 | {
88 | ///
89 | /// 数据库里面的语言后缀
90 | ///
91 | public string Suffix { get; set; }
92 | ///
93 | /// 数据库语言的VALUE
94 | ///
95 | public int LanguageValue { get; set; }
96 | ///
97 | /// 需要全局替换的字符串Key(用于替换默认语言)
98 | ///
99 | public string ReplaceViewStringKey = "LanguageId=1";
100 | ///
101 | /// 需要全局替换的字符串Value(用于替换默认语言)
102 | ///
103 | public string ReplaceViewStringValue = "LanguageId = {0}";
104 |
105 | }
106 | ///
107 | /// SqlSugarClient通用常量
108 | ///
109 | internal class SqlSugarClientConst {
110 | ///
111 | /// 属性设置错误信息
112 | ///
113 | public const string AttrMappingError = @"[SugarMapping(ColumnName = ""{1}"")]
114 | public string {0} {{ get; set; }}已经在其存在于其它表, Columns映射只能在 {0}->{1}和{0}->{2}二者选其一";
115 | ///
116 | /// SqlQuery查询的SQL模板
117 | ///
118 | public const string SqlQuerySqlTemplate = @"--{0}
119 | {1}";
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Tool/IEnumerableExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Reflection;
6 | using System.Data;
7 | using System.Data.SqlTypes;
8 |
9 | namespace SqlSugar
10 | {
11 | ///
12 | /// ** 描述:IEnumerable扩展类
13 | /// ** 创始时间:2015-6-9
14 | /// ** 修改时间:-
15 | /// ** 作者:sunkaixuan
16 | /// ** 使用说明:
17 | ///
18 | public static class IEnumerableExtensions
19 | {
20 |
21 | static Type _guidType = typeof(Guid);
22 |
23 | #region 单组
24 | ///
25 | /// 排序
26 | ///
27 | ///
28 | ///
29 | ///
30 | ///
31 | ///
32 | public static IOrderedEnumerable OrderBy(this IEnumerable list, string sortField, OrderByType orderByType)
33 | {
34 | var type = typeof(T);
35 | PropertyInfo prop = type.GetProperty(sortField);
36 | Check.Exception(prop == null, "No property '" + sortField + "' in + " + typeof(T).Name + "'");
37 | if (orderByType == OrderByType.Desc)
38 | return list.OrderByDescending(it => ConvertField(prop.GetValue(it, null)));
39 | else
40 | return list.OrderBy(it => ConvertField(prop.GetValue(it, null)));
41 |
42 |
43 | }
44 | ///
45 | /// 排序
46 | ///
47 | ///
48 | ///
49 | ///
50 | ///
51 | ///
52 | public static IOrderedEnumerable ThenBy(this IOrderedEnumerable list, string sortField, OrderByType orderByType)
53 | {
54 | var type = typeof(T);
55 | PropertyInfo prop = type.GetProperty(sortField);
56 | Check.Exception(prop == null, "No property '" + sortField + "' in + " + typeof(T).Name + "'");
57 | if (orderByType == OrderByType.Desc)
58 | return list.ThenByDescending(it => ConvertField(prop.GetValue(it, null)));
59 | else
60 | return list.ThenBy(it => ConvertField(prop.GetValue(it, null)));
61 |
62 | }
63 |
64 | ///
65 | /// 排序
66 | ///
67 | ///
68 | ///
69 | ///
70 | ///
71 | ///
72 | public static IOrderedEnumerable OrderByDataRow(this IEnumerable list, string sortField, OrderByType orderByType) where T : DataRow
73 | {
74 | var type = typeof(T);
75 | PropertyInfo prop = type.GetProperty(sortField);
76 | if (orderByType == OrderByType.Desc)
77 | return list.OrderByDescending(it => ConvertField(it[sortField]));
78 | else
79 | return list.OrderBy(it => ConvertField(it[sortField]));
80 |
81 | }
82 |
83 | ///
84 | /// 排序
85 | ///
86 | ///
87 | ///
88 | ///
89 | ///
90 | ///
91 | public static IOrderedEnumerable ThenByDataRow(this IOrderedEnumerable list, string sortField, OrderByType orderByType) where T : DataRow
92 | {
93 | var type = typeof(T);
94 | PropertyInfo prop = type.GetProperty(sortField);
95 | if (orderByType == OrderByType.Desc)
96 | return list.ThenByDescending(it => ConvertField(it[sortField]));
97 | else
98 | return list.ThenBy(it => ConvertField(it[sortField]));
99 | }
100 | #endregion
101 |
102 | ///
103 | /// 解决GUID在SQL和C#中,排序方式不一致
104 | ///
105 | ///
106 | ///
107 | private static object ConvertField(object thisValue)
108 | {
109 | if (thisValue == null) return null;
110 | var isGuid = thisValue.GetType() == _guidType;
111 | if (isGuid)
112 | {
113 | return SqlGuid.Parse(thisValue.ToString());
114 | }
115 | else
116 | {
117 | return thisValue;
118 | }
119 | }
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | [Xx]64/
19 | [Xx]86/
20 | [Bb]uild/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 |
85 | # Visual Studio profiler
86 | *.psess
87 | *.vsp
88 | *.vspx
89 | *.sap
90 |
91 | # TFS 2012 Local Workspace
92 | $tf/
93 |
94 | # Guidance Automation Toolkit
95 | *.gpState
96 |
97 | # ReSharper is a .NET coding add-in
98 | _ReSharper*/
99 | *.[Rr]e[Ss]harper
100 | *.DotSettings.user
101 |
102 | # JustCode is a .NET coding add-in
103 | .JustCode
104 |
105 | # TeamCity is a build add-in
106 | _TeamCity*
107 |
108 | # DotCover is a Code Coverage Tool
109 | *.dotCover
110 |
111 | # NCrunch
112 | _NCrunch_*
113 | .*crunch*.local.xml
114 | nCrunchTemp_*
115 |
116 | # MightyMoose
117 | *.mm.*
118 | AutoTest.Net/
119 |
120 | # Web workbench (sass)
121 | .sass-cache/
122 |
123 | # Installshield output folder
124 | [Ee]xpress/
125 |
126 | # DocProject is a documentation generator add-in
127 | DocProject/buildhelp/
128 | DocProject/Help/*.HxT
129 | DocProject/Help/*.HxC
130 | DocProject/Help/*.hhc
131 | DocProject/Help/*.hhk
132 | DocProject/Help/*.hhp
133 | DocProject/Help/Html2
134 | DocProject/Help/html
135 |
136 | # Click-Once directory
137 | publish/
138 |
139 | # Publish Web Output
140 | *.[Pp]ublish.xml
141 | *.azurePubxml
142 |
143 | # TODO: Un-comment the next line if you do not want to checkin
144 | # your web deploy settings because they may include unencrypted
145 | # passwords
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # NuGet Packages
150 | *.nupkg
151 | # The packages folder can be ignored because of Package Restore
152 | **/packages/*
153 | # except build/, which is used as an MSBuild target.
154 | !**/packages/build/
155 | # Uncomment if necessary however generally it will be regenerated when needed
156 | #!**/packages/repositories.config
157 | # NuGet v3's project.json files produces more ignoreable files
158 | *.nuget.props
159 | *.nuget.targets
160 |
161 | # Microsoft Azure Build Output
162 | csx/
163 | *.build.csdef
164 |
165 | # Microsoft Azure Emulator
166 | ecf/
167 | rcf/
168 |
169 | # Microsoft Azure ApplicationInsights config file
170 | ApplicationInsights.config
171 |
172 | # Windows Store app package directory
173 | AppPackages/
174 | BundleArtifacts/
175 |
176 | # Visual Studio cache files
177 | # files ending in .cache can be ignored
178 | *.[Cc]ache
179 | # but keep track of directories ending in .cache
180 | !*.[Cc]ache/
181 |
182 | # Others
183 | ClientBin/
184 | [Ss]tyle[Cc]op.*
185 | ~$*
186 | *~
187 | *.dbmdl
188 | *.dbproj.schemaview
189 | *.pfx
190 | *.publishsettings
191 | node_modules/
192 | orleans.codegen.cs
193 |
194 | # RIA/Silverlight projects
195 | Generated_Code/
196 |
197 | # Backup & report files from converting an old project file
198 | # to a newer Visual Studio version. Backup files are not needed,
199 | # because we have git ;-)
200 | _UpgradeReport_Files/
201 | Backup*/
202 | UpgradeLog*.XML
203 | UpgradeLog*.htm
204 |
205 | # SQL Server files
206 | *.mdf
207 | *.ldf
208 |
209 | # Business Intelligence projects
210 | *.rdl.data
211 | *.bim.layout
212 | *.bim_*.settings
213 |
214 | # Microsoft Fakes
215 | FakesAssemblies/
216 |
217 | # GhostDoc plugin setting file
218 | *.GhostDoc.xml
219 |
220 | # Node.js Tools for Visual Studio
221 | .ntvs_analysis.dat
222 |
223 | # Visual Studio 6 build log
224 | *.plg
225 |
226 | # Visual Studio 6 workspace options file
227 | *.opt
228 |
229 | # Visual Studio LightSwitch build output
230 | **/*.HTMLClient/GeneratedArtifacts
231 | **/*.DesktopClient/GeneratedArtifacts
232 | **/*.DesktopClient/ModelManifest.xml
233 | **/*.Server/GeneratedArtifacts
234 | **/*.Server/ModelManifest.xml
235 | _Pvt_Extensions
236 |
237 | # LightSwitch generated files
238 | GeneratedArtifacts/
239 | ModelManifest.xml
240 |
241 | # Paket dependency manager
242 | .paket/paket.exe
243 |
244 | # FAKE - F# Make
245 | .fake/
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Tool/LanguageHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace SqlSugar
7 | {
8 | ///
9 | /// ** 描述:多语言视图帮助类
10 | /// ** 创始时间:2016-8-7
11 | /// ** 修改时间:-
12 | /// ** 作者:孙凯旋
13 | /// ** 使用说明:
14 | ///
15 | public class LanguageHelper
16 | {
17 | ///
18 | /// 多语言视图的前缀
19 | ///
20 | public static string PreSuffix = "_$_";
21 | ///
22 | /// 获取所有需要生成多语言的视图名称
23 | ///
24 | ///
25 | ///
26 | internal static List GetLanguageViewNameList(SqlSugarClient db)
27 | {
28 | string key = "LanguageHelper.GetViewNameList";
29 | var cm = CacheManager>.GetInstance();
30 | if (cm.ContainsKey(key))
31 | {
32 | return cm[key];
33 | }
34 | else
35 | {
36 | var list = db.SqlQuery(@"
37 | select a.name from sys.objects a
38 | JOIN sys.sql_modules b on a.[object_id]=b.[object_id]
39 | where [type]='v'
40 | and b.[definition] like '%" + db.Language.ReplaceViewStringKey + @"%'
41 | and a.name not like '%"+PreSuffix+@"%'
42 | ").ToList();
43 | cm.Add(key, list, cm.Day);
44 | return list;
45 | }
46 |
47 | }
48 |
49 | ///
50 | /// 创建多语言视图,带有LanguageId=1的所有有视图1替换成languageValue 并且新创视图 名称为 原有视图名+_$_+suffix
51 | ///
52 | ///
53 | public static void UpdateView(PubModel.Language lan, SqlSugarClient db)
54 | {
55 | if (lan == null) return;
56 | if (lan.Suffix.IsNullOrEmpty())
57 | {
58 | Check.Exception(true, "LanguageHelper.lan.Suffix is Null Or Empty");
59 | }
60 | if (PreSuffix.IsNullOrEmpty())
61 | {
62 | Check.Exception(true, "LanguageHelper.PreSuffix is Null Or Empty");
63 | }
64 |
65 |
66 | if (!lan.Suffix.StartsWith(PreSuffix))
67 | {
68 | lan.Suffix = PreSuffix + lan.Suffix;
69 | }
70 |
71 | string sql = @"
72 |
73 | --验证参数传递规则
74 | if LEFT(ltrim(@Suffix),3)<>'" + PreSuffix + @"'
75 | begin
76 | raiserror('参数传递格式不规范',16,1)
77 | return;
78 | end
79 | else
80 | if(ISNULL("+lan.LanguageValue+@",'')='')
81 | begin
82 | raiserror('参数传递格式不规范',16,1)
83 | return;
84 | end
85 |
86 | declare
87 | @name varchar(100), --视图名称
88 | @definition varchar(max) --视图脚本
89 | --删除数据库里面所有带传递参数几号的视图
90 | declare my_cursor cursor for
91 | select a.name,b.[definition] from sys.objects a
92 | JOIN sys.sql_modules b on a.[object_id]=b.[object_id]
93 | where [type]='v'
94 | and b.[definition] like '%" + lan.ReplaceViewStringKey + @"%'
95 | and a.name not like '%"+PreSuffix+@"%'
96 | --打开处理器
97 | open my_cursor
98 | fetch next from my_cursor into @name,@definition
99 | while @@FETCH_STATUS=0
100 | begin
101 | --脚本查询语言ID更改,并且更改新脚本语言的对象名称
102 | set @definition=REPLACE(
103 | REPLACE(
104 | @definition,
105 | '" + lan.ReplaceViewStringKey + @"',
106 | '" + string.Format(lan.ReplaceViewStringValue, lan.LanguageValue) + @"'
107 | ),
108 | @name,
109 | @name+@Suffix
110 | )
111 | --判断新脚本语言的对象名称是否存在,存在删除
112 | exec(
113 | '
114 | if object_id('''+@name+@Suffix+''',''v'') is not null
115 | begin
116 | drop view '+@name+@Suffix+'
117 | end
118 |
119 | '
120 | )
121 | exec(@definition)
122 | fetch next from my_cursor into @name,@definition
123 | end
124 | close my_cursor
125 | deallocate my_cursor
126 | ";
127 |
128 | db.ExecuteCommand(sql, new { Suffix = lan.Suffix });
129 |
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/SqlSugarCore/src/SqlSugarForCore/Tool/SqlSugarToolCoreDiff.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Data;
6 | using System.Data.SqlClient;
7 |
8 | namespace SqlSugar
9 | {
10 | ///
11 | /// SqlSugarTool局部类与Core有差异的部分(方便工具移植到.NetCore版本)
12 | ///
13 | public partial class SqlSugarTool
14 | {
15 | private static void FillValueTypeToDictionary(Type type, IDataReader dr, List strReval)
16 | {
17 | using (IDataReader re = dr)
18 | {
19 | Dictionary reval = new Dictionary();
20 | while (re.Read())
21 | {
22 | if (SqlSugarTool.DicOO == type)
23 | {
24 | var kv = new KeyValuePair