├── src ├── MySqlSugarForCore │ ├── nuget.bat │ ├── NuGet.exe │ ├── obj │ │ └── Debug │ │ │ └── netstandard1.6 │ │ │ ├── .SDKVersion │ │ │ ├── dotnet-compile.assemblyinfo.cs │ │ │ └── .IncrementalCache │ ├── mySqlSugarCore.3.5.2.6.nupkg │ ├── bin │ │ └── Debug │ │ │ └── netstandard1.6 │ │ │ ├── MySqlSugarForCore.dll │ │ │ └── MySqlSugarForCore.pdb │ ├── MySqlSugarForCore.xproj.user │ ├── 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 │ ├── PubModel │ │ ├── KeyValue.cs │ │ ├── PubEnum.cs │ │ └── PubModel.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Core │ │ ├── ResolveExpress │ │ │ ├── Property.cs │ │ │ ├── Models.cs │ │ │ ├── Constant.cs │ │ │ ├── ResolveFieldName.cs │ │ │ ├── ResolveSelect.cs │ │ │ └── Method.cs │ │ └── IDataRecordExtensions.cs │ ├── Sqlable │ │ └── Sqlable.cs │ ├── MySqlSugarForCore.xproj │ ├── MySqlSugarForCore.nuspec │ ├── Base │ │ └── TypeExtensions.cs │ ├── Generating │ │ ├── ClassTemplate.cs │ │ └── SugarAttribute.cs │ ├── Cloud │ │ ├── CloudPubMethod.cs │ │ └── CloudModels.cs │ └── Queryable │ │ └── Queryable.cs └── NewTest │ ├── obj │ └── Debug │ │ └── netcoreapp1.0 │ │ ├── .SDKVersion │ │ ├── dotnet-compile.assemblyinfo.cs │ │ └── .IncrementalCache │ ├── bin │ └── Debug │ │ └── netcoreapp1.0 │ │ ├── NewTest.dll │ │ ├── NewTest.pdb │ │ ├── MySqlSugarForCore.dll │ │ ├── MySqlSugarForCore.pdb │ │ ├── NewTest.runtimeconfig.dev.json │ │ └── NewTest.runtimeconfig.json │ ├── Demos │ ├── IDemos.cs │ ├── SerializerDateFormat.cs │ ├── Tran.cs │ ├── Ado.cs │ ├── Delete.cs │ ├── PubMethod.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 │ ├── NewTest.xproj.user │ ├── Models │ ├── StudentGroup.cs │ ├── Area.cs │ ├── School.cs │ ├── Subject.cs │ ├── LanguageTest.cs │ ├── V_LanguageTest.cs │ ├── Student.cs │ ├── TestUpdateColumns.cs │ ├── Student2.cs │ ├── V_Student.cs │ └── InsertTest.cs │ ├── project.json │ ├── Properties │ └── AssemblyInfo.cs │ ├── Dao │ └── SugarDao.cs │ ├── NewTest.xproj │ ├── Program.cs │ └── DataBase │ └── sqlsugartest.sql ├── global.json ├── .vs ├── MySqlSugarForCore │ └── v14 │ │ └── .suo └── restore.dg └── MySqlSugarForCore.sln /src/MySqlSugarForCore/nuget.bat: -------------------------------------------------------------------------------- 1 | %~dp0nuget.exe pack %~dp0MySqlSugarForCore.nuspec -OutputDirectory %~dp0 -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "projects": [ "src", "test" ], 3 | "sdk": { 4 | "version": "1.0.0-preview2-003131" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/NewTest/obj/Debug/netcoreapp1.0/.SDKVersion: -------------------------------------------------------------------------------- 1 | 635cf40e58ede8a53e8b9555e19a6e1ccd6f9fbe 2 | 1.0.0-preview2-003131 3 | 4 | win10-x64 -------------------------------------------------------------------------------- /.vs/MySqlSugarForCore/v14/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/.vs/MySqlSugarForCore/v14/.suo -------------------------------------------------------------------------------- /src/MySqlSugarForCore/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/MySqlSugarForCore/NuGet.exe -------------------------------------------------------------------------------- /src/MySqlSugarForCore/obj/Debug/netstandard1.6/.SDKVersion: -------------------------------------------------------------------------------- 1 | 635cf40e58ede8a53e8b9555e19a6e1ccd6f9fbe 2 | 1.0.0-preview2-003131 3 | 4 | win10-x64 -------------------------------------------------------------------------------- /src/NewTest/bin/Debug/netcoreapp1.0/NewTest.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/NewTest/bin/Debug/netcoreapp1.0/NewTest.dll -------------------------------------------------------------------------------- /src/NewTest/bin/Debug/netcoreapp1.0/NewTest.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/NewTest/bin/Debug/netcoreapp1.0/NewTest.pdb -------------------------------------------------------------------------------- /src/MySqlSugarForCore/mySqlSugarCore.3.5.2.6.nupkg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/MySqlSugarForCore/mySqlSugarCore.3.5.2.6.nupkg -------------------------------------------------------------------------------- /src/NewTest/bin/Debug/netcoreapp1.0/MySqlSugarForCore.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/NewTest/bin/Debug/netcoreapp1.0/MySqlSugarForCore.dll -------------------------------------------------------------------------------- /src/NewTest/bin/Debug/netcoreapp1.0/MySqlSugarForCore.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/NewTest/bin/Debug/netcoreapp1.0/MySqlSugarForCore.pdb -------------------------------------------------------------------------------- /src/NewTest/bin/Debug/netcoreapp1.0/NewTest.runtimeconfig.dev.json: -------------------------------------------------------------------------------- 1 | { 2 | "runtimeOptions": { 3 | "additionalProbingPaths": [ 4 | "C:\\Users\\skx\\.nuget\\packages" 5 | ] 6 | } 7 | } -------------------------------------------------------------------------------- /src/NewTest/bin/Debug/netcoreapp1.0/NewTest.runtimeconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "runtimeOptions": { 3 | "framework": { 4 | "name": "Microsoft.NETCore.App", 5 | "version": "1.0.1" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /src/MySqlSugarForCore/bin/Debug/netstandard1.6/MySqlSugarForCore.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/MySqlSugarForCore/bin/Debug/netstandard1.6/MySqlSugarForCore.dll -------------------------------------------------------------------------------- /src/MySqlSugarForCore/bin/Debug/netstandard1.6/MySqlSugarForCore.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DotNetNext/ASP_NET_CORE_ORM_MySqlSugar/HEAD/src/MySqlSugarForCore/bin/Debug/netstandard1.6/MySqlSugarForCore.pdb -------------------------------------------------------------------------------- /.vs/restore.dg: -------------------------------------------------------------------------------- 1 | #:F:\MyOpenSource\MySqlCode\MySqlSugarForCore\src\NewTest\NewTest.xproj 2 | F:\MyOpenSource\MySqlCode\MySqlSugarForCore\src\NewTest\NewTest.xproj|F:\MyOpenSource\MySqlCode\MySqlSugarForCore\src\MySqlSugarForCore\MySqlSugarForCore.xproj 3 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/NewTest.xproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NewTest 5 | 6 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/MySqlSugarForCore.xproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Start 5 | 6 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/obj/Debug/netstandard1.6/dotnet-compile.assemblyinfo.cs: -------------------------------------------------------------------------------- 1 | // This file has been auto generated. 2 | [assembly:System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] 3 | [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETStandard,Version=v1.6")] -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "dependencies": { 4 | "MySql.Data": "7.0.5-IR21", 5 | "NETStandard.Library": "1.6.0", 6 | "System.Reflection.Emit.Lightweight": "4.0.1" 7 | }, 8 | "frameworks": { 9 | "netstandard1.6": { 10 | "imports": "dnxcore50" 11 | } 12 | }, 13 | "buildOptions": { 14 | "xmlDoc": true 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/NewTest/obj/Debug/netcoreapp1.0/dotnet-compile.assemblyinfo.cs: -------------------------------------------------------------------------------- 1 | // This file has been auto generated. 2 | [assembly:System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] 3 | [assembly:System.Reflection.AssemblyVersionAttribute("1.0.0.0")] 4 | [assembly:System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] 5 | [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v1.0")] -------------------------------------------------------------------------------- /src/NewTest/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 | "MySql.Data": "7.0.5-IR21", 13 | "MySqlSugarForCore": "1.0.0-*", 14 | "System.Text.Encoding.CodePages": "4.0.1" 15 | }, 16 | 17 | "frameworks": { 18 | "netcoreapp1.0": { 19 | "imports": "dnxcore50" 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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("NewTest")] 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("da9f097b-af65-429a-9bab-7e9c684f3ecf")] 20 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/IStorageObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace MySqlSugar 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 | } -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/PubModel/KeyValue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/Dao/SugarDao.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using MySqlSugar; 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=localhost;Database=SqlSugarTest;Uid=root;Pwd=root"; //这里可以动态根据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 | } -------------------------------------------------------------------------------- /src/MySqlSugarForCore/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("MySqlSugarForCore")] 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.4")] 21 | [assembly: AssemblyFileVersion("3.5.4")] -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Core/ResolveExpress/Property.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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("不支持属性扩展方法" + methodName + "。"); 18 | } 19 | } 20 | private string ProLength(string value, bool isField) 21 | { 22 | if (isField) 23 | { 24 | return string.Format("length({0})", value.GetTranslationSqlName()); 25 | } 26 | else 27 | { 28 | return string.Format("{0}", value.ObjToString().Length); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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.CommandTimeOut = 30000;//设置超时时间 22 | try 23 | { 24 | db.BeginTran();//开启事务 25 | //db.BeginTran(IsolationLevel.ReadCommitted);+3重载可以设置事世隔离级别 26 | 27 | db.CommitTran();//提交事务 28 | } 29 | catch (Exception) 30 | { 31 | db.RollbackTran();//回滚事务 32 | throw; 33 | } 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/NewTest.xproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 10 | da9f097b-af65-429a-9bab-7e9c684f3ecf 11 | NewTest 12 | .\obj 13 | .\bin\ 14 | v4.5.2 15 | 16 | 17 | 18 | 2.0 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Sqlable/Sqlable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using MySql.Data.MySqlClient; 6 | 7 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/MySqlSugarForCore.xproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 16e4a140-f463-48a8-b126-070d63092b13 10 | MySqlSugarForCore 11 | .\obj 12 | .\bin\ 13 | v4.5.2 14 | 15 | 16 | 2.0 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/Check.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/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 | using MySql.Data.MySqlClient; 9 | 10 | namespace NewTest.Demos 11 | { 12 | //完美兼容SqlHelper的所有功能 13 | public class Ado:IDemos 14 | { 15 | 16 | public void Init() 17 | { 18 | Console.WriteLine("启动Ado.Init"); 19 | using (var db = SugarDao.GetInstance()) 20 | { 21 | var r1 = db.GetDataTable("select * from student"); 22 | var r2 = db.GetSingle("select * from student LIMIT 0,1"); 23 | var r3 = db.GetScalar("select count(1) from student"); 24 | var r4 = db.GetReader("select count(1) from student"); 25 | r4.Dispose(); 26 | var r5 = db.GetString("select name from student LIMIT 0,1"); 27 | var r6 = db.ExecuteCommand("select 1"); 28 | 29 | 30 | //参数支持 31 | var p1 = db.GetDataTable("select * from student where id=@id", new {id=1 }); 32 | var p2 = db.GetDataTable("select * from student where id=@id", new Dictionary() { { "id", "1" } });//目前只支持 Dictionary和Dictionary 33 | var p3 = db.GetDataTable("select * from student where id=@id", new MySqlParameter("@id",1) ); 34 | 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/NewTest/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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/PubModel/PubEnum.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | } 65 | /// 66 | /// 解析类型 67 | /// 68 | public enum ResolveExpressType 69 | { 70 | /// 71 | /// 单个T 72 | /// 73 | OneT = 0, 74 | /// 75 | /// 多个T 76 | /// 77 | NT = 1, 78 | 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/MySqlSugarForCore.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | mySqlSugarCore 5 | 3.5.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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Core/ResolveExpress/Models.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /MySqlSugarForCore.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", "{722432B2-E99E-44EA-94C9-F53C0F79FF9C}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CF799644-EA4C-441E-900F-2814DEF7F5E4}" 9 | ProjectSection(SolutionItems) = preProject 10 | global.json = global.json 11 | EndProjectSection 12 | EndProject 13 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "MySqlSugarForCore", "src\MySqlSugarForCore\MySqlSugarForCore.xproj", "{16E4A140-F463-48A8-B126-070D63092B13}" 14 | EndProject 15 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "NewTest", "src\NewTest\NewTest.xproj", "{DA9F097B-AF65-429A-9BAB-7E9C684F3ECF}" 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 | {16E4A140-F463-48A8-B126-070D63092B13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {16E4A140-F463-48A8-B126-070D63092B13}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {16E4A140-F463-48A8-B126-070D63092B13}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {16E4A140-F463-48A8-B126-070D63092B13}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {DA9F097B-AF65-429A-9BAB-7E9C684F3ECF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {DA9F097B-AF65-429A-9BAB-7E9C684F3ECF}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {DA9F097B-AF65-429A-9BAB-7E9C684F3ECF}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {DA9F097B-AF65-429A-9BAB-7E9C684F3ECF}.Release|Any CPU.Build.0 = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(SolutionProperties) = preSolution 33 | HideSolutionNode = FALSE 34 | EndGlobalSection 35 | GlobalSection(NestedProjects) = preSolution 36 | {16E4A140-F463-48A8-B126-070D63092B13} = {722432B2-E99E-44EA-94C9-F53C0F79FF9C} 37 | {DA9F097B-AF65-429A-9BAB-7E9C684F3ECF} = {722432B2-E99E-44EA-94C9-F53C0F79FF9C} 38 | EndGlobalSection 39 | EndGlobal 40 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/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 MySqlSugar 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&&type!=SqlSugarTool.StringType; 69 | } 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Generating/ClassTemplate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/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 MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 * from Student limit 0,1", "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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/SqlException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using MySqlSugar; 6 | using NewTest.Demos; 7 | using System.Text; 8 | 9 | namespace NewTest 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 | //配置与实例的用法 67 | case "initconfig": demo = new InitConfig(); break; 68 | 69 | 70 | 71 | /****************************支持**************************************/ 72 | //公开函数数 73 | case "pubmethod": demo = new PubMethod(); break; 74 | 75 | //设置ToJson的日期格式 76 | case "serializerdateformat": demo = new SerializerDateFormat(); break; 77 | 78 | 79 | 80 | /****************************测试用例**************************************/ 81 | case "test": demo = new Test(); break; 82 | 83 | default: Console.WriteLine("switchOn的值错误,请输入正确的 case"); break; 84 | 85 | } 86 | //执行DEMO 87 | demo.Init(); 88 | 89 | //更多例子请查看API 90 | //http://www.cnblogs.com/sunkaixuan/p/5654695.html 91 | Console.WriteLine("执行成功请关闭窗口"); 92 | Console.ReadKey(); 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Core/ResolveExpress/Constant.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 7 | { 8 | //局部类:拉姆达解析公用常量 9 | internal partial class ResolveExpress 10 | { 11 | /// 12 | /// 解析bool类型用到的字典 13 | /// 14 | public static List ConstantBoolDictionary = new List() 15 | { 16 | new ExpressBoolModel(){ Key=Guid.NewGuid(), OldValue="True", Type=SqlSugarTool.StringType}, 17 | new ExpressBoolModel(){ Key=Guid.NewGuid(), OldValue="False",Type=SqlSugarTool.StringType}, 18 | new ExpressBoolModel(){ Key=Guid.NewGuid(), OldValue="True",Type=SqlSugarTool.BoolType}, 19 | new ExpressBoolModel(){ Key=Guid.NewGuid(), OldValue="False",Type=SqlSugarTool.BoolType} 20 | 21 | }; 22 | /// 23 | /// 字段名解析错误 24 | /// 25 | public const string FileldErrorMessage = "OrderBy、GroupBy、In、Min和Max等操作不是有效拉姆达格式 ,正确格式 it=>it.name "; 26 | /// 27 | /// 拉姆达解析错误 28 | /// 29 | public const string ExpToSqlError= @"拉姆达解析出错,不是有效的函数,找不到合适函数你可以使用这种字符串写法.Where(""date>dateadd(@date)"",new{date=DateTime.Now}), 30 | 支持的函数有(请复制到本地查看,数量比较多): 31 | db.Queryable().Where(it => it.field == parValue.ObjToString()); 32 | db.Queryable().Where(it => it.field == parValue.ObjToDate()); 33 | db.Queryable().Where(it => it.field == parValue.ObjToInt()) 34 | db.Queryable().Where(it => it.field == parValue.ObjToDecimal()) 35 | db.Queryable().Where(it => it.field == parValue.ObjToMoney()) 36 | db.Queryable().Where(it => it.field == parValue.Trim()) 37 | db.Queryable().Where(it => it.field == parValue.ToString()) 38 | db.Queryable().Where(it => it.field == Convert.ToXXX(parValue)) 39 | db.Queryable().Where(it => it.field.Contains(parValue)) 40 | db.Queryable().Where(it => it.field.StartsWith(parValue)) 41 | db.Queryable().Where(it => it.field.EndsWith(parValue)) 42 | db.Queryable().Where(it => !string.IsNullOrEmpty(it.parValue)) 43 | db.Queryable().Where(it => arrayOrList.Contains(it.parValue)) 44 | db.Queryable().Where(it => it.field.Equals(it.parValue)) 45 | db.Queryable().Where(it => it.field.Length>10) 46 | db.Queryable().Where(c => c.field == parValue.ToLower()).ToList(); 47 | db.Queryable().Where(c => c.field == parValue.ToUpper()).ToList(); 48 | "; 49 | /// 50 | /// 运算符错误 51 | /// 52 | public const string OperatorError = "拉姆达解析出错:不支持{0}此种运算符查找!"; 53 | 54 | /// 55 | /// 拉姆达解析唯一标识 56 | /// 57 | public static object ExpErrorUniqueKey = Guid.NewGuid(); 58 | 59 | /// 60 | /// 拉姆达函数错误 61 | /// 62 | public const string ExpMethodError = "拉姆达表达式中的函数用法不正确,正确写法 it=>it.name.{0}(参数) ,不支持的写法it=> 参数.{0}(it.name)。"; 63 | 64 | 65 | /// 66 | /// 拉姆达函数错误2 67 | /// 68 | public const string ExpMethodError2 = "拉姆达表达式中的函数用法不正确,正确写法 it=>it.name==参数.{0} ,不支持的写法it=>it.name.{0}==参数。"; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/NewTest/obj/Debug/netcoreapp1.0/.IncrementalCache: -------------------------------------------------------------------------------- 1 | {"inputs":["F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\project.json","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\project.lock.json","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Program.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Dao\\SugarDao.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Ado.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\AttributesMapping.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\CreateClass.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Delete.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\EnumDemo.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Filter.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Filter2.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\IDemos.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\IgnoreErrorColumns.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\InitConfig.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Insert.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Log.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\MappingColumns.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\MappingTable.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\PubMethod.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Select.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\SerializerDateFormat.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\SerialNumber.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Test.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Tran.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Demos\\Update.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\Area.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\InsertTest.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\LanguageTest.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\School.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\Student.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\Student2.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\StudentGroup.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\Subject.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\TestUpdateColumns.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\V_LanguageTest.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Models\\V_Student.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\Properties\\AssemblyInfo.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\bin\\Debug\\netstandard1.6\\MySqlSugarForCore.dll"],"outputs":["F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\bin\\Debug\\netcoreapp1.0\\NewTest.dll","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\bin\\Debug\\netcoreapp1.0\\NewTest.pdb","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\bin\\Debug\\netcoreapp1.0\\NewTest.deps.json","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\NewTest\\bin\\Debug\\netcoreapp1.0\\NewTest.runtimeconfig.json"],"buildArguments":{"version-suffix":null}} -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/NewTest/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 MySqlSugar; 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/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 MySqlSugar 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/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 MySqlSugar 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/PubModel/PubModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/NewTest/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 | db.Update("sch_id=sch_id+1", it => it.id == 1); 68 | 69 | 70 | //清空禁止更新列 71 | db.DisableUpdateColumns = null; 72 | //新语法添加禁止更新列 73 | db.AddDisableUpdateColumns("id", "name");//添加禁止更新列 74 | 75 | } 76 | } 77 | 78 | 79 | 80 | private static List GetUpdateList() 81 | { 82 | List list = new List() 83 | { 84 | new Student() 85 | { 86 | id=1001, 87 | name="1张1001"+new Random().Next(1,int.MaxValue) 88 | }, 89 | new Student() 90 | { 91 | id=1002, 92 | name="1张1002"+new Random().Next(1,int.MaxValue) 93 | } 94 | }; 95 | return list; 96 | } 97 | private static List GetUpdateList2() 98 | { 99 | List list = new List() 100 | { 101 | new Student() 102 | { 103 | id=1010, 104 | name="小妹"+new Random().Next(1,int.MaxValue), 105 | isOk=false, 106 | sch_id=2, 107 | sex="gril" 108 | }, 109 | new Student() 110 | { 111 | id=1011, 112 | name="小子"+new Random().Next(1,int.MaxValue), 113 | isOk=true, 114 | sch_id=3, 115 | sex="boy" 116 | } 117 | }; 118 | return list; 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Cloud/CloudPubMethod.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace MySqlSugar 8 | { 9 | 10 | internal class CloudPubMethod 11 | { 12 | public static Random random = new Random(); 13 | 14 | /// 15 | /// 获取pageIndex 16 | /// 17 | /// 18 | /// 19 | public static int GetPageIndex(int pageIndex, double configCount) 20 | { 21 | var index = pageIndex / configCount; 22 | if (index <= 1) 23 | { 24 | index = 1; 25 | } 26 | else if (pageIndex % configCount != 0) 27 | { 28 | index = (int)index + 1; 29 | } 30 | return (int)index; 31 | } 32 | 33 | /// 34 | /// 根据rate获取随机Connection 35 | /// 36 | /// 37 | public static string GetConnection(List configList) 38 | { 39 | Check.Exception(configList == null || configList.Count == 0, "CloudPubMethod.GetConnection.configList不能为null并且count>0。"); 40 | List connectionNameList = new List(); 41 | SetConnectionNameList(configList, ref connectionNameList); 42 | var index = random.Next(0, connectionNameList.Count); 43 | return connectionNameList[index]; 44 | } 45 | 46 | /// 47 | /// 并行执行任务并且传入索引 48 | /// 49 | /// 函数参数i 50 | /// task数组 51 | /// 索引 52 | public static void TaskFactory(Func method, Task[] tasks, int i) 53 | { 54 | tasks[i] = Task.Factory.StartNew(() => 55 | { 56 | return method(i); 57 | }); ; 58 | } 59 | 60 | 61 | private static void SetConnectionNameList(List configList, ref List connectionNameList) 62 | { 63 | var cacheKey = "SetConnectionNameList"; 64 | var cm = CacheManager>.GetInstance(); 65 | if (cm.ContainsKey(cacheKey)) 66 | { 67 | connectionNameList = cm[cacheKey]; 68 | } 69 | else 70 | { 71 | foreach (CloudConnectionConfig config in configList) 72 | { 73 | for (int i = 0; i < config.Rate; i++) 74 | { 75 | connectionNameList.Add(config.ConnectionString); 76 | } 77 | } 78 | cm.Add(cacheKey, connectionNameList, cm.Day); 79 | } 80 | } 81 | /// 82 | /// 分页索引是否很小 83 | /// 84 | /// 85 | /// 86 | /// 87 | /// 88 | /// 89 | public static bool GetIsSmallPageIndex(int pageIndex, int pageSize, int configCount, int maxHandleNumber) 90 | { 91 | if (pageIndex <= configCount) 92 | { 93 | return pageIndex * pageSize * configCount <= maxHandleNumber; 94 | 95 | } 96 | return false; 97 | } 98 | /// 99 | /// 倒数分页索引是否很小 100 | /// 101 | /// 102 | /// 103 | /// 104 | /// 105 | /// 106 | /// 107 | public static bool GetIsSmallPageIndexByReverse(int totalPage, int pageIndex, int pageSize, int configCount, int maxHandleNumber) 108 | { 109 | //倒数第几页 110 | var lastPage=(totalPage - pageIndex)+1 ; 111 | if (lastPage <= configCount) 112 | { 113 | return lastPage * pageSize <= maxHandleNumber; 114 | } 115 | return false; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/obj/Debug/netstandard1.6/.IncrementalCache: -------------------------------------------------------------------------------- 1 | {"inputs":["F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\project.json","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\project.lock.json","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\SqlSugarClient.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Base\\DataTableExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Base\\SqlHelper.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Base\\TypeExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Cloud\\CloudModels.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Cloud\\CloudPubMethod.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\IDataReaderEntityBuilder.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\IDataRecordExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\Constant.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\Expressions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\Main.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\Method.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\Models.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\Property.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\ResolveFieldName.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Core\\ResolveExpress\\ResolveSelect.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Generating\\ClassGenerating.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Generating\\ClassTemplate.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Generating\\SugarAttribute.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Properties\\AssemblyInfo.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\PubModel\\KeyValue.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\PubModel\\PubEnum.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\PubModel\\PubModel.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Queryable\\Queryable.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Queryable\\QueryableExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Sqlable\\Sqlable.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Sqlable\\SqlableExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\CacheManager.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\Check.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\FileSugar.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\IEnumerableExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\IStorageObject.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\IsWhatExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\JsonConverter.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\LanguageHelper.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\PubConvert.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\SqlException.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\SqlSugarTool.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\SqlSugarToolCoreDiff.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\SqlSugarToolExtensions.cs","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\Tool\\SqlSugarToolWithSqlMethod.cs"],"outputs":["F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\bin\\Debug\\netstandard1.6\\MySqlSugarForCore.dll","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\bin\\Debug\\netstandard1.6\\MySqlSugarForCore.pdb","F:\\MyOpenSource\\MySqlCode\\MySqlSugarForCore\\src\\MySqlSugarForCore\\bin\\Debug\\netstandard1.6\\MySqlSugarForCore.xml"],"buildArguments":{"version-suffix":null}} -------------------------------------------------------------------------------- /src/MySqlSugarForCore/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 MySqlSugar 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/LanguageHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 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 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/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 MySqlSugar 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(dr.GetValue(0), re.GetValue(1)); 25 | strReval.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair))); 26 | } 27 | else if (SqlSugarTool.Dicii == type) 28 | { 29 | var kv = new KeyValuePair(dr.GetValue(0).ObjToInt(), re.GetValue(1).ObjToInt()); 30 | strReval.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair))); 31 | } 32 | else if (SqlSugarTool.DicSi == type) 33 | { 34 | var kv = new KeyValuePair(dr.GetValue(0).ObjToString(), re.GetValue(1).ObjToInt()); 35 | strReval.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair))); 36 | } 37 | else if (SqlSugarTool.DicSo == type) 38 | { 39 | var kv = new KeyValuePair(dr.GetValue(0).ObjToString(), re.GetValue(1)); 40 | strReval.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair))); 41 | } 42 | else if (SqlSugarTool.DicSS == type) 43 | { 44 | var kv = new KeyValuePair(dr.GetValue(0).ObjToString(), dr.GetValue(1).ObjToString()); 45 | strReval.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair))); 46 | } 47 | else 48 | { 49 | Check.Exception(true, "暂时不支持该类型的Dictionary 你可以试试 Dictionary或者联系作者!!"); 50 | } 51 | } 52 | } 53 | } 54 | private static void FillValueTypeToArray(Type type, IDataReader dr, List strReval) 55 | { 56 | using (IDataReader re = dr) 57 | { 58 | int count = dr.FieldCount; 59 | var childType = type.GetElementType(); 60 | while (re.Read()) 61 | { 62 | object[] array = new object[count]; 63 | 64 | if (childType == SqlSugarTool.StringType) 65 | strReval.Add((T)Convert.ChangeType(array.Select(it => it.ObjToString()).ToArray(), type)); 66 | else if (childType == SqlSugarTool.ObjType) 67 | strReval.Add((T)Convert.ChangeType(array.Select(it => it).ToArray(), type)); 68 | else if (childType == SqlSugarTool.BoolType) 69 | strReval.Add((T)Convert.ChangeType(array.Select(it => it.ObjToBool()).ToArray(), type)); 70 | else if (childType == SqlSugarTool.ByteType) 71 | strReval.Add((T)Convert.ChangeType(array.Select(it => (byte)it).ToArray(), type)); 72 | else if (childType == SqlSugarTool.DecType) 73 | strReval.Add((T)Convert.ChangeType(array.Select(it => it.ObjToDecimal()).ToArray(), type)); 74 | else if (childType == SqlSugarTool.GuidType) 75 | strReval.Add((T)Convert.ChangeType(array.Select(it => Guid.Parse(it.ObjToString())).ToArray(), type)); 76 | else if (childType == SqlSugarTool.DateType) 77 | strReval.Add((T)Convert.ChangeType(array.Select(it => it.ObjToDate()).ToArray(), type)); 78 | else if (childType == SqlSugarTool.IntType) 79 | strReval.Add((T)Convert.ChangeType(array.Select(it => it.ObjToInt()).ToArray(), type)); 80 | else 81 | Check.Exception(true, "暂时不支持该类型的Array 你可以试试 object[] 或者联系作者!!"); 82 | } 83 | } 84 | } 85 | 86 | /// 87 | /// 获取参数到键值集合根据页面Request参数 88 | /// 89 | /// 90 | public static Dictionary GetParameterDictionary(bool isNotNullAndEmpty = false) 91 | { 92 | throw new SqlSugarException("Core版枯不支持该函数"); 93 | } 94 | 95 | /// 96 | /// 获取参数到键值集合根据页面Request参数 97 | /// 98 | /// 99 | public static SqlParameter[] GetParameterArray(bool isNotNullAndEmpty = false) 100 | { 101 | throw new SqlSugarException("Core版枯不支持该函数"); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/NewTest/DataBase/sqlsugartest.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat MySQL Data Transfer 3 | 4 | Source Server : mysql 5 | Source Server Version : 50547 6 | Source Host : localhost:3306 7 | Source Database : sqlsugartest 8 | 9 | Target Server Type : MYSQL 10 | Target Server Version : 50547 11 | File Encoding : 65001 12 | 13 | Date: 2016-10-20 04:24:18 14 | */ 15 | 16 | SET FOREIGN_KEY_CHECKS=0; 17 | 18 | -- ---------------------------- 19 | -- Table structure for area 20 | -- ---------------------------- 21 | DROP TABLE IF EXISTS `area`; 22 | CREATE TABLE `area` ( 23 | `Id` int(11) NOT NULL AUTO_INCREMENT, 24 | `name` varchar(255) NOT NULL, 25 | PRIMARY KEY (`Id`) 26 | ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=gbk; 27 | 28 | -- ---------------------------- 29 | -- Records of area 30 | -- ---------------------------- 31 | INSERT INTO `area` VALUES ('1', '上海'); 32 | INSERT INTO `area` VALUES ('2', '北京'); 33 | INSERT INTO `area` VALUES ('3', '南通'); 34 | INSERT INTO `area` VALUES ('4', '日本'); 35 | 36 | -- ---------------------------- 37 | -- Table structure for inserttest 38 | -- ---------------------------- 39 | DROP TABLE IF EXISTS `inserttest`; 40 | CREATE TABLE `inserttest` ( 41 | `id` int(11) NOT NULL AUTO_INCREMENT, 42 | `v1` varchar(255) DEFAULT NULL, 43 | `v2` varchar(255) DEFAULT NULL, 44 | `v3` varchar(255) DEFAULT NULL, 45 | `int1` int(255) DEFAULT NULL, 46 | `d1` datetime DEFAULT NULL, 47 | `txt` varchar(255) DEFAULT NULL, 48 | PRIMARY KEY (`id`) 49 | ) ENGINE=MyISAM DEFAULT CHARSET=gbk; 50 | 51 | -- ---------------------------- 52 | -- Records of inserttest 53 | -- ---------------------------- 54 | 55 | -- ---------------------------- 56 | -- Table structure for school 57 | -- ---------------------------- 58 | DROP TABLE IF EXISTS `school`; 59 | CREATE TABLE `school` ( 60 | `id` int(11) NOT NULL AUTO_INCREMENT, 61 | `name` varchar(500) NOT NULL, 62 | `AreaId` int(11) DEFAULT NULL, 63 | PRIMARY KEY (`id`) 64 | ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=gbk; 65 | 66 | -- ---------------------------- 67 | -- Records of school 68 | -- ---------------------------- 69 | INSERT INTO `school` VALUES ('1', '北大青鸟', '1'); 70 | INSERT INTO `school` VALUES ('2', 'IT清华', '2'); 71 | INSERT INTO `school` VALUES ('3', '全智', '3'); 72 | INSERT INTO `school` VALUES ('4', '黑马', '2'); 73 | INSERT INTO `school` VALUES ('5', '幼儿园', '3'); 74 | INSERT INTO `school` VALUES ('6', '蓝翔', '1'); 75 | 76 | -- ---------------------------- 77 | -- Table structure for student 78 | -- ---------------------------- 79 | DROP TABLE IF EXISTS `student`; 80 | CREATE TABLE `student` ( 81 | `id` int(11) NOT NULL AUTO_INCREMENT, 82 | `name` varchar(500) DEFAULT NULL, 83 | `sch_id` int(11) DEFAULT NULL COMMENT '学校编号', 84 | `sex` varchar(500) DEFAULT NULL, 85 | `isOk` bit(1) DEFAULT NULL, 86 | PRIMARY KEY (`id`) 87 | ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=gbk; 88 | 89 | -- ---------------------------- 90 | -- Records of student 91 | -- ---------------------------- 92 | INSERT INTO `student` VALUES ('1', '小杰', '1', 'boy', ''); 93 | INSERT INTO `student` VALUES ('2', '小明', '2', 'grid', '\0'); 94 | INSERT INTO `student` VALUES ('3', '张三', '3', 'boy', ''); 95 | INSERT INTO `student` VALUES ('4', '李四', '2', 'grid', '\0'); 96 | INSERT INTO `student` VALUES ('5', '王五', '3', 'boy', ''); 97 | INSERT INTO `student` VALUES ('6', '小姐', '1', 'grid', '\0'); 98 | INSERT INTO `student` VALUES ('7', '小捷', '3', 'grid', ''); 99 | INSERT INTO `student` VALUES ('8', '小J', '1', 'grid', ''); 100 | 101 | -- ---------------------------- 102 | -- Table structure for subject 103 | -- ---------------------------- 104 | DROP TABLE IF EXISTS `subject`; 105 | CREATE TABLE `subject` ( 106 | `id` int(11) NOT NULL AUTO_INCREMENT, 107 | `studentId` int(11) DEFAULT NULL, 108 | `name` varchar(255) DEFAULT NULL, 109 | PRIMARY KEY (`id`) 110 | ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=gbk; 111 | 112 | -- ---------------------------- 113 | -- Records of subject 114 | -- ---------------------------- 115 | INSERT INTO `subject` VALUES ('1', '1', '语文'); 116 | INSERT INTO `subject` VALUES ('2', '2', '数学'); 117 | INSERT INTO `subject` VALUES ('3', '4', '.NET'); 118 | INSERT INTO `subject` VALUES ('4', '5', 'JAVA'); 119 | INSERT INTO `subject` VALUES ('5', '6', 'IOS'); 120 | INSERT INTO `subject` VALUES ('6', '7', 'PHP'); 121 | 122 | -- ---------------------------- 123 | -- Table structure for test 124 | -- ---------------------------- 125 | DROP TABLE IF EXISTS `test`; 126 | CREATE TABLE `test` ( 127 | `Id` int(11) NOT NULL AUTO_INCREMENT, 128 | PRIMARY KEY (`Id`) 129 | ) ENGINE=MyISAM DEFAULT CHARSET=gbk; 130 | 131 | -- ---------------------------- 132 | -- Records of test 133 | -- ---------------------------- 134 | 135 | -- ---------------------------- 136 | -- Table structure for testupdatecolumns 137 | -- ---------------------------- 138 | DROP TABLE IF EXISTS `testupdatecolumns`; 139 | CREATE TABLE `testupdatecolumns` ( 140 | `VGUID` varchar(255) NOT NULL DEFAULT '', 141 | `Name` varchar(255) DEFAULT NULL, 142 | `Name2` varchar(255) DEFAULT NULL, 143 | `IdentityField` int(11) NOT NULL, 144 | `CreateTime` datetime DEFAULT NULL, 145 | PRIMARY KEY (`VGUID`) 146 | ) ENGINE=MyISAM DEFAULT CHARSET=gbk; 147 | 148 | -- ---------------------------- 149 | -- Records of testupdatecolumns 150 | -- ---------------------------- 151 | INSERT INTO `testupdatecolumns` VALUES ('6DF396EB-D1C8-48A5-8BE1-D58D685646A7', 'xx', 'xx2', '0', '2015-01-01 00:00:00'); 152 | 153 | -- ---------------------------- 154 | -- View structure for v_name 155 | -- ---------------------------- 156 | DROP VIEW IF EXISTS `v_name`; 157 | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` VIEW `v_name` AS select 1 as id ; 158 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Cloud/CloudModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data; 6 | using System.Threading.Tasks; 7 | 8 | namespace MySqlSugar 9 | { 10 | 11 | /// 12 | /// 云计算连接配置 13 | /// 14 | public class CloudConnectionConfig 15 | { 16 | /// 17 | /// 处理机率,值越大机率越高 18 | /// 19 | public int Rate { get; set; } 20 | /// 21 | /// 链接字符串名称 22 | /// 23 | public string ConnectionString { get; set; } 24 | } 25 | 26 | /// 27 | /// 云搜索Task反回类 28 | /// 29 | public class CloudSearchResult 30 | { 31 | /// 32 | /// 集合 33 | /// 34 | public List Entities { get; set; } 35 | /// 36 | /// 单个对象 37 | /// 38 | public T Value { get; set; } 39 | /// 40 | /// DataTable 41 | /// 42 | public DataTable DataTable { get; set; } 43 | /// 44 | /// 连接字符串 45 | /// 46 | public string ConnectionString { get; set; } 47 | /// 48 | /// 数量 49 | /// 50 | public int Count { get; set; } 51 | } 52 | 53 | 54 | 55 | /// 56 | /// 云计扩展类 57 | /// 58 | /// 59 | public class Taskable 60 | { 61 | /// 62 | /// 任务 63 | /// 64 | public Task>[] Tasks { get; set; } 65 | /// 66 | /// sql 67 | /// 68 | public string Sql { get; set; } 69 | /// 70 | /// 数据库参数(例如:new{id=1,name="张三"}) 71 | /// 72 | public object WhereObj { get; set; } 73 | 74 | } 75 | 76 | /// 77 | /// 云计扩展类 78 | /// 79 | /// 80 | public class TaskableWithCount 81 | { 82 | /// 83 | /// 任务 84 | /// 85 | public Task>[] Tasks { get; set; } 86 | /// 87 | /// sql 88 | /// 89 | public string Sql { get; set; } 90 | /// 91 | /// 数据库参数(例如:new{id=1,name="张三"}) 92 | /// 93 | public object WhereObj { get; set; } 94 | 95 | } 96 | 97 | internal class PageRowInnerParamsResult 98 | { 99 | public DataRow Row { get; set; } 100 | public int Count { get; set; } 101 | public int PageIndex { get; set; } 102 | public int PageSize { get; set; } 103 | public int Begin { get; set; } 104 | public int End { get; set; } 105 | public string Sql { get; set; } 106 | public bool IsEqs { get; set; } 107 | public string OrderByField { get; set; } 108 | public string UnqueField { get; set; } 109 | public int RowIndex { get; set; } 110 | public bool isGreater { get; set; } 111 | public string Symbol { get; set; } 112 | public object OrderByValue { get; set; } 113 | public object UnqueValue { get; set; } 114 | public OrderByType OrderByType { get; set; } 115 | public string FullOrderByString { get; set; } 116 | public string FullOrderByStringReverse { get; set; } 117 | public object WhereObj { get; set; } 118 | public string SymbolReverse { get; set; } 119 | public int ConfigCount { get; set; } 120 | public OrderByType OrderByTypeReverse { get; set; } 121 | } 122 | 123 | internal class PageRowInnerParamsResultMultipleOrderBy 124 | { 125 | public DataRow Row { get; set; } 126 | public int Count { get; set; } 127 | public int PageIndex { get; set; } 128 | public int PageSize { get; set; } 129 | public int Begin { get; set; } 130 | public int End { get; set; } 131 | public string Sql { get; set; } 132 | public string UnqueField { get; set; } 133 | public int RowIndex { get; set; } 134 | public bool isGreater { get; set; } 135 | public object UnqueValue { get; set; } 136 | public string FullOrderByString { get; set; } 137 | public string FullOrderByStringReverse { get; set; } 138 | public object WhereObj { get; set; } 139 | public int ConfigCount { get; set; } 140 | 141 | public string orderByFieldsString { get; set; } 142 | 143 | public List OrderByTypes { get; set; } 144 | 145 | public int SampleEachIndex { get; set; } 146 | } 147 | 148 | /// 149 | /// 字典排序类 150 | /// 151 | public class OrderByDictionary 152 | { 153 | /// 154 | /// 排序字段 155 | /// 156 | public string OrderByField { get; set; } 157 | /// 158 | /// 排序类型 159 | /// 160 | public OrderByType OrderByType { get; set; } 161 | /// 162 | /// 排序字符串 163 | /// 164 | public string OrderByString 165 | { 166 | get 167 | { 168 | return string.Format(" {0} {1} ", OrderByField, OrderByType.ToString()); 169 | } 170 | } 171 | /// 172 | /// 排序字符返转 173 | /// 174 | public string OrderByStringReverse 175 | { 176 | get 177 | { 178 | return string.Format(" {0} {1} ", OrderByField, OrderByTypeReverse.ToString()); 179 | } 180 | } 181 | /// 182 | /// 排序字符返转 183 | /// 184 | public OrderByType OrderByTypeReverse 185 | { 186 | get 187 | { 188 | return IsAsc ? OrderByType.desc : OrderByType.asc; 189 | } 190 | } 191 | /// 192 | /// 是升序 193 | /// 194 | public bool IsAsc 195 | { 196 | get 197 | { 198 | return OrderByType == OrderByType.asc; 199 | } 200 | } 201 | /// 202 | /// 比较符 203 | /// 204 | public string Symbol 205 | { 206 | get 207 | { 208 | return IsAsc ? "<" : ">"; 209 | } 210 | } 211 | /// 212 | /// 比较符反转 213 | /// 214 | public string SymbolReverse 215 | { 216 | get 217 | { 218 | return IsAsc ? ">" : "<"; 219 | } 220 | } 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/SqlSugarToolExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.RegularExpressions; 6 | using MySql.Data.MySqlClient; 7 | 8 | namespace MySqlSugar 9 | { 10 | /// 11 | /// ** 描述:SqlSugar扩展工具类 12 | /// ** 创始时间:2015-7-19 13 | /// ** 修改时间:- 14 | /// ** 作者:sunkaixuan 15 | /// ** 使用说明: 16 | /// 17 | public static class SqlSugarToolExtensions 18 | { 19 | 20 | /// 21 | /// 将数组转换成Where In 需要的格式(例如:参数 new int{1,2,3} 反回 "'1','2','3'") 22 | /// 23 | /// 24 | /// 25 | public static string ToJoinSqlInVal(this T[] array) 26 | { 27 | if (array == null || array.Length == 0) 28 | { 29 | return ToSqlValue(string.Empty); 30 | } 31 | else 32 | { 33 | return string.Join(",", array.Where(c => c != null).Select(it => (it + "").ToSuperSqlFilter().ToSqlValue())); 34 | } 35 | } 36 | /// 37 | /// 将字符串转换成SQL参数所需要的格式(例如: 参数value返回'value') 38 | /// 39 | /// 40 | /// 41 | public static string ToSqlValue(this string value) 42 | { 43 | return string.Format("'{0}'", value.ToSqlFilter()); 44 | } 45 | /// 46 | ///SQL注入过滤 47 | /// 48 | /// 49 | /// 50 | public static string ToSqlFilter(this string value) 51 | { 52 | if (!value.IsNullOrEmpty()) 53 | { 54 | value = value.Replace("'", "''");//转释单引 55 | } 56 | return value; 57 | } 58 | /// 59 | /// 指定数据类型,如果不在指定类当中则引发异常(只允许输入指定字母、数字、下划线、时间、GUID) 60 | /// 61 | /// 62 | /// 63 | public static string ToSuperSqlFilter(this string value) 64 | { 65 | if (!value.IsNullOrEmpty()) 66 | { 67 | value = value.Replace("'", "''");//转释单引 68 | } 69 | return value; 70 | } 71 | 72 | /// 73 | /// 获取锁字符串 74 | /// 75 | /// 76 | /// 77 | internal static string GetLockString(this bool isNoLock) 78 | { 79 | return isNoLock ? "WITH(NOLOCK)" : null; ; 80 | } 81 | /// 82 | /// 获取Select需要的字段 83 | /// 84 | /// 85 | /// 86 | internal static string GetSelectFiles(this string selectFileds) 87 | { 88 | return selectFileds.IsNullOrEmpty() ? "*" : selectFileds; 89 | } 90 | /// 91 | /// 92 | /// 93 | /// 94 | /// 95 | internal static string GetGroupBy(this string groupByFileds) 96 | { 97 | return groupByFileds.IsNullOrEmpty() ? "" : " GROUP BY " + groupByFileds; 98 | } 99 | /// 100 | /// 将Request里的参数转成SqlParameter[] 101 | /// 102 | /// 103 | internal static void RequestParasToSqlParameters(MySqlParameterCollection oldParas) 104 | { 105 | var oldParaList = oldParas.Cast().ToList(); 106 | var paraDictionarAll = SqlSugarTool.GetParameterDictionary(); 107 | if (paraDictionarAll != null && paraDictionarAll.Count() > 0) 108 | { 109 | 110 | foreach (KeyValuePair it in paraDictionarAll) 111 | { 112 | 113 | var par = new MySqlParameter("@" + it.Key, it.Value); 114 | if (!oldParaList.Any(oldPara => oldPara.ParameterName == ("@" + it.Key))) 115 | { 116 | oldParas.Add(par); 117 | } 118 | } 119 | } 120 | } 121 | /// 122 | /// 获取转释后的表名和列名 123 | /// 124 | /// 125 | /// 126 | public static string GetTranslationSqlName(this string tableName) 127 | { 128 | return SqlSugarTool.GetTranslationSqlName(tableName); 129 | } 130 | /// 131 | /// 获取参数名 132 | /// 133 | /// 134 | /// 135 | internal static string GetSqlParameterName(this string name) 136 | { 137 | return SqlSugarTool.GetSqlParameterName(name); 138 | } 139 | 140 | /// 141 | ///获取没有符号的参数名称 142 | /// 143 | /// 144 | /// 145 | internal static string GetSqlParameterNameNoParSymbol(this string name) 146 | { 147 | return SqlSugarTool.GetSqlParameterNameNoParSymbol(name); 148 | } 149 | 150 | /// 151 | /// 数组条件筛选 152 | /// 153 | /// 154 | /// 155 | /// 156 | internal static string[] ArrayWhere(this string[] thisValue, Func expression) 157 | { 158 | if (thisValue == null) return null; 159 | thisValue = thisValue.Where(expression).ToArray(); 160 | return thisValue; 161 | } 162 | 163 | /// 164 | /// 数组添加元素 165 | /// 166 | /// 167 | /// 168 | /// 169 | internal static string[] ArrayAdd(this string[] thisValue, params string[] items) 170 | { 171 | if (thisValue == null) thisValue = new string[] { }; 172 | var reval = thisValue.ToList(); 173 | reval.AddRange(items); 174 | thisValue = reval.ToArray(); 175 | return thisValue; 176 | } 177 | 178 | /// 179 | /// 数组移除 180 | /// 181 | /// 182 | /// 183 | /// 184 | internal static string[] ArrayRemove(this string[] thisValue, string item) 185 | { 186 | if (thisValue == null) thisValue = new string[] { }; 187 | var reval = thisValue.ToList(); 188 | reval.Remove(item); 189 | thisValue = reval.ToArray(); 190 | return thisValue; 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/CacheManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Collections; 6 | using System.Linq.Expressions; 7 | 8 | namespace MySqlSugar 9 | { 10 | /// 11 | /// ** 描述:缓存操作类 12 | /// ** 创始时间:2015-6-9 13 | /// ** 修改时间:- 14 | /// ** 作者:sunkaixuan 15 | /// ** 使用说明:http://www.cnblogs.com/sunkaixuan/p/4563462.html 16 | /// 17 | /// 值类型 18 | internal class CacheManager : IStorageObject 19 | { 20 | 21 | readonly System.Collections.Concurrent.ConcurrentDictionary InstanceCache = new System.Collections.Concurrent.ConcurrentDictionary(); 22 | 23 | #region 全局变量 24 | private static CacheManager _instance = null; 25 | private static readonly object _instanceLock = new object(); 26 | #endregion 27 | 28 | #region 构造函数 29 | 30 | private CacheManager() { } 31 | #endregion 32 | 33 | #region 属性 34 | /// 35 | ///根据key获取value 36 | /// 37 | /// 38 | public override V this[string key] 39 | { 40 | get 41 | { 42 | return this.Get(key); 43 | } 44 | } 45 | #endregion 46 | 47 | #region 公共函数 48 | 49 | /// 50 | /// 验证key是否存在 51 | /// 52 | /// key 53 | /// /// 存在true 不存在false. /// /// 54 | public override bool ContainsKey(string key) 55 | { 56 | return this.InstanceCache.ContainsKey(key); 57 | 58 | //throw new NotImplementedException(); 59 | //return HttpRuntime.Cache[CreateKey(key)] != null; 60 | } 61 | 62 | /// 63 | /// 根据key获取value 64 | /// 65 | /// key 66 | /// 67 | public override V Get(string key) 68 | { 69 | if (this.ContainsKey(key)) 70 | return this.InstanceCache[key]; 71 | else 72 | return default(V); 73 | } 74 | 75 | /// 76 | /// 获取实例 (单例模式) 77 | /// 78 | /// 79 | public static CacheManager GetInstance() 80 | { 81 | if (_instance == null) 82 | lock (_instanceLock) 83 | if (_instance == null) 84 | _instance = new CacheManager(); 85 | return _instance; 86 | } 87 | 88 | /// 89 | /// 插入缓存(默认20分钟) 90 | /// 91 | /// key 92 | /// value 93 | public override void Add(string key, V value) 94 | { 95 | this.InstanceCache.GetOrAdd(key, value); 96 | } 97 | 98 | /// 99 | /// 插入缓存 100 | /// 101 | /// key 102 | /// value 103 | /// 过期时间单位秒 104 | public void Add(string key, V value, int cacheDurationInSeconds) 105 | { 106 | Add(key, value); 107 | } 108 | 109 | ///// 110 | ///// 插入缓存. 111 | ///// 112 | ///// key 113 | ///// value 114 | ///// 过期时间单位秒 115 | ///// 缓存项属性 116 | //public void Add(string key, V value, int cacheDurationInSeconds, CacheItemPriority priority) 117 | //{ 118 | // string keyString = CreateKey(key); 119 | // HttpRuntime.Cache.Insert(keyString, value, null, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null); 120 | //} 121 | 122 | ///// 123 | ///// 插入缓存. 124 | ///// 125 | ///// key 126 | ///// value 127 | ///// 过期时间单位秒 128 | ///// 缓存项属性 129 | //public void Add(string key, V value, int cacheDurationInSeconds, CacheDependency dependency, CacheItemPriority priority) 130 | //{ 131 | // //string keyString = CreateKey(key); 132 | // //HttpRuntime.Cache.Insert(keyString, value, dependency, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null); 133 | //} 134 | 135 | /// 136 | /// 删除缓存 137 | /// 138 | /// key 139 | public override void Remove(string key) 140 | { 141 | V val; 142 | this.InstanceCache.TryRemove(key, out val); 143 | 144 | //throw new NotImplementedException(); 145 | //HttpRuntime.Cache.Remove(CreateKey(key)); 146 | } 147 | 148 | /// 149 | /// 清除所有缓存 150 | /// 151 | public override void RemoveAll() 152 | { 153 | this.InstanceCache.Clear(); 154 | 155 | } 156 | 157 | /// 158 | /// 清除所有缓存 159 | /// 160 | /// 表达式条件 161 | public override void RemoveAll(Func removeExpression) 162 | { 163 | //throw new NotImplementedException(); 164 | //System.Web.Caching.Cache _cache = HttpRuntime.Cache; 165 | var allKeyList = GetAllKey(); 166 | var delKeyList = allKeyList.Where(removeExpression).ToList(); 167 | foreach (var key in delKeyList) 168 | { 169 | Remove(key); 170 | } 171 | } 172 | 173 | /// 174 | /// 获取所有缓存key 175 | /// 176 | /// 177 | public override IEnumerable GetAllKey() 178 | { 179 | return this.InstanceCache.Keys; 180 | 181 | //throw new NotImplementedException(); 182 | //IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator(); 183 | //while (CacheEnum.MoveNext()) 184 | //{ 185 | // yield return CacheEnum.Key.ToString(); 186 | //} 187 | } 188 | #endregion 189 | 190 | 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/PubConvert.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace MySqlSugar 7 | { 8 | /// 9 | /// ** 描述:公用转换函数 10 | /// ** 创始时间:2015-6-9 11 | /// ** 修改时间:- 12 | /// ** 作者:sunkaixuan 13 | /// ** 使用说明: 14 | /// 15 | public static class PubConvert 16 | { 17 | #region 强转成int 如果失败返回 0 18 | /// 19 | /// 强转成int 如果失败返回 0 20 | /// 21 | /// 22 | /// 23 | public static int ObjToInt(this object thisValue) 24 | { 25 | int reval = 0; 26 | if (thisValue == null) return 0; 27 | if (thisValue.GetType().IsEnum()) return Convert.ToInt32(thisValue); 28 | if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval)) 29 | { 30 | return reval; 31 | } 32 | return reval; 33 | } 34 | #endregion 35 | #region 强转成int 如果失败返回 errorValue 36 | /// 37 | /// 强转成int 如果失败返回 errorValue 38 | /// 39 | /// 40 | /// 41 | /// 42 | public static int ObjToInt(this object thisValue, int errorValue) 43 | { 44 | int reval = 0; 45 | if (thisValue != null &&thisValue != DBNull.Value&& int.TryParse(thisValue.ToString(), out reval)) 46 | { 47 | return reval; 48 | } 49 | return errorValue; 50 | } 51 | #endregion 52 | #region 强转成double 如果失败返回 0 53 | /// 54 | /// 强转成money 如果失败返回 0 55 | /// 56 | /// 57 | /// 58 | public static double ObjToMoney(this object thisValue) 59 | { 60 | double reval = 0; 61 | if (thisValue != null &&thisValue != DBNull.Value&& double.TryParse(thisValue.ToString(), out reval)) 62 | { 63 | return reval; 64 | } 65 | return 0; 66 | } 67 | #endregion 68 | #region 强转成double 如果失败返回 errorValue 69 | /// 70 | /// 强转成double 如果失败返回 errorValue 71 | /// 72 | /// 73 | /// 74 | /// 75 | public static double ObjToMoney(this object thisValue, double errorValue) 76 | { 77 | double reval = 0; 78 | if (thisValue != null &&thisValue != DBNull.Value&& double.TryParse(thisValue.ToString(), out reval)) 79 | { 80 | return reval; 81 | } 82 | return errorValue; 83 | } 84 | #endregion 85 | #region 强转成string 如果失败返回 "" 86 | /// 87 | /// 强转成string 如果失败返回 "" 88 | /// 89 | /// 90 | /// 91 | public static string ObjToString(this object thisValue) 92 | { 93 | if (thisValue != null) return thisValue.ToString().Trim(); 94 | return ""; 95 | } 96 | #endregion 97 | #region 强转成string 如果失败返回 errorValue 98 | /// 99 | /// 强转成string 如果失败返回 str 100 | /// 101 | /// 102 | /// 103 | /// 104 | public static string ObjToString(this object thisValue, string errorValue) 105 | { 106 | if (thisValue != null) return thisValue.ToString().Trim(); 107 | return errorValue; 108 | } 109 | #endregion 110 | #region 强转成Decimal 如果失败返回 0 111 | /// 112 | /// 强转成Decimal 如果失败返回 0 113 | /// 114 | /// 115 | /// 116 | public static Decimal ObjToDecimal(this object thisValue) 117 | { 118 | Decimal reval = 0; 119 | if (thisValue != null &&thisValue != DBNull.Value&& decimal.TryParse(thisValue.ToString(), out reval)) 120 | { 121 | return reval; 122 | } 123 | return 0; 124 | } 125 | #endregion 126 | #region 强转成Decimal 如果失败返回 errorValue 127 | /// 128 | /// 强转成Decimal 如果失败返回 errorValue 129 | /// 130 | /// 131 | /// 132 | /// 133 | public static Decimal ObjToDecimal(this object thisValue, decimal errorValue) 134 | { 135 | Decimal reval = 0; 136 | if (thisValue != null &&thisValue != DBNull.Value&& decimal.TryParse(thisValue.ToString(), out reval)) 137 | { 138 | return reval; 139 | } 140 | return errorValue; 141 | } 142 | #endregion 143 | #region 强转成DateTime 如果失败返回 DateTime.MinValue 144 | /// 145 | /// 强转成DateTime 如果失败返回 DateTime.MinValue 146 | /// 147 | /// 148 | /// 149 | public static DateTime ObjToDate(this object thisValue) 150 | { 151 | DateTime reval = DateTime.MinValue; 152 | if (thisValue != null &&thisValue != DBNull.Value&& DateTime.TryParse(thisValue.ToString(), out reval)) 153 | { 154 | return reval; 155 | } 156 | return reval; 157 | } 158 | #endregion 159 | #region 强转成DateTime 如果失败返回 errorValue 160 | /// 161 | /// 强转成DateTime 如果失败返回 errorValue 162 | /// 163 | /// 164 | /// 165 | /// 166 | public static DateTime ObjToDate(this object thisValue, DateTime errorValue) 167 | { 168 | DateTime reval = DateTime.MinValue; 169 | if (thisValue != null &&thisValue != DBNull.Value&& DateTime.TryParse(thisValue.ToString(), out reval)) 170 | { 171 | return reval; 172 | } 173 | return errorValue; 174 | } 175 | #endregion 176 | #region 强转成Bool 如果失败返回 false 177 | /// 178 | /// 强转成Bool 如果失败返回 false 179 | /// 180 | /// 181 | /// 182 | public static bool ObjToBool(this object thisValue) 183 | { 184 | bool reval = false; 185 | if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval)) 186 | { 187 | return reval; 188 | } 189 | return reval; 190 | } 191 | #endregion 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Core/IDataRecordExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Data; 6 | 7 | namespace MySqlSugar 8 | { 9 | /// 10 | /// ** 描述:IDataRecord扩展类 11 | /// ** 创始时间:2016-8-7 12 | /// ** 修改时间:- 13 | /// ** 作者:孙凯旋 14 | /// ** 使用说明: 15 | /// 16 | public static class IDataRecordExtensions 17 | { 18 | /// 19 | /// 获取bool 20 | /// 21 | /// 22 | /// 23 | /// 24 | public static bool? GetConvertBoolean(this IDataRecord dr, int i) 25 | { 26 | if (dr.IsDBNull(i)) 27 | { 28 | return null; 29 | } 30 | var reval = dr.GetBoolean(i); 31 | return reval; 32 | } 33 | 34 | /// 35 | /// 获取byte 36 | /// 37 | /// 38 | /// 39 | /// 40 | public static byte? GetConvertByte(this IDataRecord dr, int i) 41 | { 42 | if (dr.IsDBNull(i)) 43 | { 44 | return null; 45 | } 46 | var reval = dr.GetByte(i); 47 | return reval; 48 | } 49 | 50 | /// 51 | /// 获取char 52 | /// 53 | /// 54 | /// 55 | /// 56 | public static char? GetConvertChar(this IDataRecord dr, int i) 57 | { 58 | if (dr.IsDBNull(i)) 59 | { 60 | return null; 61 | } 62 | var reval = dr.GetChar(i); 63 | return reval; 64 | } 65 | 66 | /// 67 | /// 获取时间 68 | /// 69 | /// 70 | /// 71 | /// 72 | public static DateTime? GetConvertDateTime(this IDataRecord dr, int i) 73 | { 74 | if (dr.IsDBNull(i)) 75 | { 76 | return null; 77 | } 78 | var reval = dr.GetDateTime(i); 79 | return reval; 80 | } 81 | 82 | /// 83 | /// 获取转换Decimal 84 | /// 85 | /// 86 | /// 87 | /// 88 | public static decimal? GetConvertDecimal(this IDataRecord dr, int i) 89 | { 90 | if (dr.IsDBNull(i)) 91 | { 92 | return null; 93 | } 94 | var reval = dr.GetDecimal(i); 95 | return reval; 96 | } 97 | 98 | /// 99 | /// 获取Double 100 | /// 101 | /// 102 | /// 103 | /// 104 | public static double? GetConvertDouble(this IDataRecord dr, int i) 105 | { 106 | if (dr.IsDBNull(i)) 107 | { 108 | return null; 109 | } 110 | var reval = dr.GetDouble(i); 111 | return reval; 112 | } 113 | 114 | /// 115 | /// 获取GUID 116 | /// 117 | /// 118 | /// 119 | /// 120 | public static Guid? GetConvertGuid(this IDataRecord dr, int i) 121 | { 122 | if (dr.IsDBNull(i)) 123 | { 124 | return null; 125 | } 126 | var reval = dr.GetGuid(i); 127 | return reval; 128 | } 129 | 130 | /// 131 | /// 获取int16 132 | /// 133 | /// 134 | /// 135 | /// 136 | public static short? GetConvertInt16(this IDataRecord dr, int i) 137 | { 138 | if (dr.IsDBNull(i)) 139 | { 140 | return null; 141 | } 142 | var reval = dr.GetInt16(i); 143 | return reval; 144 | } 145 | 146 | /// 147 | /// 获取int32 148 | /// 149 | /// 150 | /// 151 | /// 152 | public static Int32? GetConvertInt32(this IDataRecord dr, int i) 153 | { 154 | if (dr.IsDBNull(i)) 155 | { 156 | return null; 157 | } 158 | var reval = dr.GetInt32(i); 159 | return reval; 160 | } 161 | 162 | /// 163 | /// 获取int64 164 | /// 165 | /// 166 | /// 167 | /// 168 | public static long? GetConvetInt64(this IDataRecord dr, int i) 169 | { 170 | if (dr.IsDBNull(i)) 171 | { 172 | return null; 173 | } 174 | var reval = dr.GetInt64(i); 175 | return reval; 176 | } 177 | 178 | /// 179 | /// 获取float 180 | /// 181 | /// 182 | /// 183 | /// 184 | public static float? GetConvertFloat(this IDataRecord dr, int i) 185 | { 186 | if (dr.IsDBNull(i)) 187 | { 188 | return null; 189 | } 190 | var reval = dr.GetFloat(i); 191 | return reval; 192 | } 193 | 194 | /// 195 | /// 获取其它类型 196 | /// 197 | /// 198 | /// 199 | /// 200 | /// 201 | public static Nullable GetOtherNull(this IDataReader dr, int i) where T : struct 202 | { 203 | if (dr.IsDBNull(i)) 204 | { 205 | return null; 206 | } 207 | return (T)Convert.ChangeType(dr.GetValue(i), typeof(T)); 208 | 209 | } 210 | 211 | /// 212 | /// 获取其它类型 213 | /// 214 | /// 215 | /// 216 | /// 217 | /// 218 | public static T GetOther(this IDataReader dr, int i) 219 | { 220 | return (T)Convert.ChangeType(dr.GetValue(i), typeof(T)); 221 | } 222 | 223 | /// 224 | /// 获取枚举 225 | /// 226 | /// 227 | /// 228 | /// 229 | /// 230 | public static Nullable GetConvertEnum_Nullable(this IDataReader dr, int i) where T : struct 231 | { 232 | if (dr.IsDBNull(i)) 233 | { 234 | return null; 235 | } 236 | object value = dr.GetValue(i); 237 | T t = (T)Enum.ToObject(typeof(T), value); 238 | return t; 239 | } 240 | 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Core/ResolveExpress/ResolveSelect.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Text; 4 | using System.Text.RegularExpressions; 5 | using System.Linq.Expressions; 6 | 7 | namespace MySqlSugar 8 | { 9 | 10 | /// 11 | /// ** 描述:解析Queryable.Select函数的参数 12 | /// ** 创始时间:2016-9-21 13 | /// ** 修改时间:- 14 | /// ** 作者:sunkaixuan 15 | /// ** qq:610262374 16 | /// ** 使用说明: 17 | /// 18 | internal class ResolveSelect 19 | { 20 | /// 21 | /// 多表情况 22 | /// 23 | /// 实体类型 24 | /// 拉姆达字符串 25 | /// 查旬对象 26 | /// 27 | internal static void GetResult(string expStr, Queryable reval, Expression exp) 28 | { 29 | var isComplexAnalysis = IsComplexAnalysis(expStr); 30 | reval.SelectValue = Regex.Match(expStr, @"(?<=\{).*?(?=\})").Value; 31 | if (reval.SelectValue.IsNullOrEmpty()) 32 | { 33 | reval.SelectValue = Regex.Match(expStr, @"[a-z,A-Z]\W* =>.*?\((.+)\)").Groups[1].Value; 34 | } 35 | var hasOutPar = expStr.Contains(SqlSugarTool.ParSymbol); 36 | if (hasOutPar)//有 37 | { 38 | var ms = Regex.Matches(expStr, @"""(\" + SqlSugarTool.ParSymbol + @"[a-z,A-Z]+)?""\.ObjTo[a-z,A-Z]+?\(\)").Cast().ToList(); 39 | foreach (var m in ms) 40 | { 41 | reval.SelectValue = reval.SelectValue.Replace(m.Groups[0].Value, m.Groups[1].Value); 42 | } 43 | } 44 | if (reval.SelectValue.IsNullOrEmpty()) 45 | { 46 | throw new SqlSugarException("Select 解析失败 ", new { selectString = reval.SelectValue }); 47 | } 48 | reval.SelectValue = reval.SelectValue.Replace("\"", "'"); 49 | reval.SelectValue = reval.SelectValue.Replace("DateTime.Now", "now()"); 50 | reval.SelectValue = ConvertFuns(reval.SelectValue, false); 51 | if (reval.DB != null && reval.DB.IsEnableAttributeMapping && reval.DB._mappingColumns.IsValuable()) 52 | { 53 | foreach (var item in reval.DB._mappingColumns) 54 | { 55 | reval.SelectValue = Regex.Replace(reval.SelectValue, @"\." + item.Key, "." + item.Value); 56 | } 57 | } 58 | reval.SelectValue = ConvertSelectValue(reval.SelectValue); 59 | } 60 | internal static string ConvertSelectValue(string selectValue) 61 | { 62 | if (selectValue.IsNullOrEmpty()) return "*"; 63 | var array = selectValue.Split(','); 64 | selectValue = string.Join(",", array.Select(it => { 65 | if (it.IsNullOrEmpty()) return it; 66 | if (!it.Contains("=")) return it; 67 | var innerArray = it.Split('=').OrderBy(a => a.Split('.').Length).ToArray(); 68 | return innerArray.Last().GetTranslationSqlName().Trim() + " AS " + innerArray.First().Trim().GetTranslationSqlName(); 69 | })); 70 | return selectValue; 71 | } 72 | 73 | private static bool IsComplexAnalysis(string expStr) 74 | { 75 | string errorFunName = null; 76 | if (expStr.IsValuable() && (expStr.Contains("+<>") || Regex.IsMatch(expStr, @"\.[a-z,A-Z,_]\w*\.[a-z,A-Z,_]\w*?(\,|\})"))) 77 | { 78 | throw new SqlSugarException("Select中的拉姆达表达式,不支持外部传参数,目前支持的写法 Where(\"1=1\",new {id=1}).Select(it=>{ id=\"" + SqlSugarTool.ParSymbol + "id\".ObjToInt()}"); 79 | } 80 | if (expStr.IsValuable() && Regex.IsMatch(expStr, @"\+|\-|\*|\/")) 81 | { 82 | throw new SqlSugarException("Select中不支持变量的运算。"); 83 | } 84 | string reg = @"(\.[a-z,A-Z,_]\w*?\(.*?\))|\=\s*[a-z,A-Z,_]\w*?\(.*?\)|\=\s*[a-z,A-Z,_]\w*?\(.*?\)|\=[a-z,A-Z,_]\w*.[a-z,A-Z,_]\w*.[a-z,A-Z,_]\w*"; 85 | if (expStr.IsValuable() & Regex.IsMatch(expStr, reg)) 86 | { 87 | var ms = Regex.Matches(expStr, reg); 88 | var errorNum = 0; 89 | foreach (Match item in ms.Cast().OrderBy(it => it.Value.Split('.').Length)) 90 | { 91 | if (item.Value == null) 92 | { 93 | errorNum++; 94 | break; 95 | } 96 | if (!item.Value.IsMatch(@"\.ObjTo|Convert|ToString")) 97 | { 98 | errorNum++; 99 | errorFunName = item.Value; 100 | break; 101 | } 102 | } 103 | if (errorNum > 0) 104 | { 105 | throw new SqlSugarException("Select中不支持函数" + errorFunName); 106 | } 107 | } 108 | return false; 109 | } 110 | /// 111 | /// 单表情况 112 | /// 113 | /// 实体类型 114 | /// 查旬对象 115 | /// 116 | internal static void GetResult(Queryable reval, Expression exp) 117 | { 118 | string expStr = reval.SelectValue; 119 | var isComplexAnalysis = IsComplexAnalysis(expStr); 120 | expStr = Regex.Match(expStr, @"(?<=\{).*?(?=\})").Value; 121 | if (expStr.IsNullOrEmpty()) 122 | { 123 | expStr = Regex.Match(reval.SelectValue, @"[a-z,A-Z]\W* =>.*?\((.+)\)").Groups[1].Value; 124 | } 125 | var hasOutPar = expStr.Contains(SqlSugarTool.ParSymbol); 126 | if (hasOutPar)//有 127 | { 128 | var ms = Regex.Matches(expStr, @"""(\" + SqlSugarTool.ParSymbol + @"[a-z,A-Z]+)?""\.ObjTo[a-z,A-Z]+?\(\)").Cast().ToList(); 129 | foreach (var m in ms) 130 | { 131 | expStr = expStr.Replace(m.Groups[0].Value, m.Groups[1].Value); 132 | } 133 | } 134 | expStr = Regex.Replace(expStr, @"(?<=\=)[^\,]*?\.", ""); 135 | if (reval.SelectValue.IsNullOrEmpty()) 136 | { 137 | throw new SqlSugarException("Select 解析失败 ", new { selectString = reval.SelectValue }); 138 | } 139 | expStr = expStr.Replace("\"", "'"); 140 | expStr = expStr.Replace("DateTime.Now", "now()"); 141 | expStr = ConvertFuns(expStr); 142 | reval.SelectValue = expStr; 143 | if (reval.DB != null && reval.DB.IsEnableAttributeMapping && reval.DB._mappingColumns.IsValuable()) 144 | { 145 | foreach (var item in reval.DB._mappingColumns) 146 | { 147 | reval.SelectValue = Regex.Replace(reval.SelectValue, @"\=" + item.Key, "=" + item.Value); 148 | } 149 | } 150 | reval.SelectValue = ConvertSelectValue(reval.SelectValue); 151 | } 152 | 153 | /// 154 | /// 替换函数 155 | /// 156 | /// 拉姆达字符串 157 | /// true为单表,false为多表 158 | /// 159 | internal static string ConvertFuns(string selectStr, bool isOneT = true) 160 | { 161 | if (isOneT == false)//多表 162 | { 163 | var hasFun = selectStr.Contains(")"); 164 | if (hasFun) 165 | { 166 | var m1 = Regex.Matches(selectStr, @"To[A-Z][a-z]+?\(Convert\((.+?)\)\)").Cast().ToList(); 167 | if (m1.IsValuable()) 168 | { 169 | foreach (var m in m1) 170 | { 171 | selectStr = selectStr.Replace(m.Groups[0].Value, m.Groups[1].Value); 172 | } 173 | } 174 | var m2 = Regex.Matches(selectStr, @"Convert\((.+?)\)\.ObjTo[a-z,A-Z]+?\(\)").Cast().ToList(); 175 | if (m2.IsValuable()) 176 | { 177 | foreach (var m in m2) 178 | { 179 | selectStr = selectStr.Replace(m.Groups[0].Value, m.Groups[1].Value); 180 | } 181 | } 182 | var m3 = Regex.Matches(selectStr, @"Convert\((.+?)\)").Cast().ToList(); 183 | if (m3.IsValuable()) 184 | { 185 | foreach (var m in m3) 186 | { 187 | selectStr = selectStr.Replace(m.Groups[0].Value, m.Groups[1].Value); 188 | } 189 | } 190 | } 191 | 192 | } 193 | else//单表 194 | { 195 | var hasObjToFun = Regex.IsMatch(selectStr, @"\)\s*\.ObjTo[a-z,A-Z]+?\(\s*\)"); 196 | if (hasObjToFun) 197 | { 198 | selectStr = Regex.Replace(selectStr, @"\)\s*\.ObjTo[a-z,A-Z]+?\(\s*\)", ""); 199 | } 200 | var hasFun = selectStr.Contains(")"); 201 | if (hasFun) 202 | { 203 | selectStr = selectStr.Replace(")", ""); 204 | selectStr = selectStr.Replace("(", ""); 205 | } 206 | } 207 | if (selectStr.Contains(".ToString")) 208 | { 209 | throw new SqlSugarException("Select中不支持ToString函数,请使用ObjectToString"); 210 | } 211 | if (selectStr.Contains("+<>")) 212 | { 213 | throw new SqlSugarException("Select中的拉姆达表达式,不支持外部传参数,目前支持的写法 Where(\"1=1\",new {id=1}).Select(it=>{ id=\"" + SqlSugarTool.ParSymbol + "id\".ObjToInt()}"); 214 | } 215 | return selectStr; 216 | } 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Tool/IsWhatExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.RegularExpressions; 6 | 7 | namespace MySqlSugar 8 | { 9 | /// 10 | /// ** 描述:逻辑判段是什么? 11 | /// ** 创始时间:2015-5-29 12 | /// ** 修改时间:- 13 | /// ** 作者:sunkaixuan 14 | /// ** 使用说明:http://www.cnblogs.com/sunkaixuan/p/4539654.html 15 | /// 16 | internal static class IsWhatExtensions 17 | { 18 | /// 19 | /// 值在的范围? 20 | /// 21 | /// 22 | /// 大于等于begin 23 | /// 小于等于end 24 | /// 25 | public static bool IsInRange(this int thisValue, int begin, int end) 26 | { 27 | return thisValue >= begin && thisValue <= end; 28 | } 29 | /// 30 | /// 值在的范围? 31 | /// 32 | /// 33 | /// 大于等于begin 34 | /// 小于等于end 35 | /// 36 | public static bool IsInRange(this DateTime thisValue, DateTime begin, DateTime end) 37 | { 38 | return thisValue >= begin && thisValue <= end; 39 | } 40 | 41 | /// 42 | /// 在里面吗? 43 | /// 44 | /// 45 | /// 46 | /// 47 | /// 48 | public static bool IsIn(this T thisValue, params T[] values) 49 | { 50 | return values.Contains(thisValue); 51 | } 52 | 53 | /// 54 | /// 在里面吗? 55 | /// 56 | /// 57 | /// 58 | /// 59 | public static bool IsContainsIn(this string thisValue, params string[] inValues) 60 | { 61 | return inValues.Any(it => thisValue.Contains(it)); 62 | } 63 | 64 | /// 65 | /// 是null或""? 66 | /// 67 | /// 68 | public static bool IsNullOrEmpty(this object thisValue) 69 | { 70 | if (thisValue == null || thisValue == DBNull.Value) return true; 71 | return thisValue.ToString() == ""; 72 | } 73 | /// 74 | /// 是null或""? 75 | /// 76 | /// 77 | public static bool IsNullOrEmpty(this Guid? thisValue) 78 | { 79 | if (thisValue == null) return true; 80 | return thisValue == Guid.Empty; 81 | } 82 | /// 83 | /// 是null或""? 84 | /// 85 | /// 86 | public static bool IsNullOrEmpty(this Guid thisValue) 87 | { 88 | if (thisValue == null) return true; 89 | return thisValue == Guid.Empty; 90 | } 91 | 92 | /// 93 | /// 有值?(与IsNullOrEmpty相反) 94 | /// 95 | /// 96 | public static bool IsValuable(this object thisValue) 97 | { 98 | if (thisValue == null || thisValue == DBNull.Value) return false; 99 | return thisValue.ToString() != ""; 100 | } 101 | /// 102 | /// 有值?(与IsNullOrEmpty相反) 103 | /// 104 | /// 105 | public static bool IsValuable(this IEnumerable thisValue) 106 | { 107 | if (thisValue == null || thisValue.Count() == 0) return false; 108 | return true; 109 | } 110 | 111 | /// 112 | /// 是零? 113 | /// 114 | /// 115 | /// 116 | public static bool IsZero(this object thisValue) 117 | { 118 | return (thisValue == null || thisValue.ToString() == "0"); 119 | } 120 | 121 | /// 122 | /// 是INT? 123 | /// 124 | /// 125 | /// 126 | public static bool IsInt(this object thisValue) 127 | { 128 | if (thisValue == null) return false; 129 | return Regex.IsMatch(thisValue.ToString(), @"^\d+$"); 130 | } 131 | /// 132 | /// 不是INT? 133 | /// 134 | /// 135 | /// 136 | public static bool IsNoInt(this object thisValue) 137 | { 138 | if (thisValue == null) return true; 139 | return !Regex.IsMatch(thisValue.ToString(), @"^\d+$"); 140 | } 141 | 142 | /// 143 | /// 是金钱? 144 | /// 145 | /// 146 | /// 147 | public static bool IsMoney(this object thisValue) 148 | { 149 | if (thisValue == null) return false; 150 | double outValue = 0; 151 | return double.TryParse(thisValue.ToString(), out outValue); 152 | } 153 | 154 | /// 155 | /// 是GUID? 156 | /// 157 | /// 158 | /// 159 | public static bool IsGuid(this object thisValue) 160 | { 161 | if (thisValue == null) return false; 162 | Guid outValue = Guid.Empty; 163 | return Guid.TryParse(thisValue.ToString(), out outValue); 164 | } 165 | 166 | /// 167 | /// 是时间? 168 | /// 169 | /// 170 | /// 171 | public static bool IsDate(this object thisValue) 172 | { 173 | if (thisValue == null) return false; 174 | DateTime outValue = DateTime.MinValue; 175 | return DateTime.TryParse(thisValue.ToString(), out outValue); 176 | } 177 | 178 | /// 179 | /// 是邮箱? 180 | /// 181 | /// 182 | /// 183 | public static bool IsEamil(this object thisValue) 184 | { 185 | if (thisValue == null) return false; 186 | return Regex.IsMatch(thisValue.ToString(), @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"); 187 | } 188 | 189 | /// 190 | /// 是手机? 191 | /// 192 | /// 193 | /// 194 | public static bool IsMobile(this object thisValue) 195 | { 196 | if (thisValue == null) return false; 197 | return Regex.IsMatch(thisValue.ToString(), @"^\d{11}$"); 198 | } 199 | 200 | /// 201 | /// 是座机? 202 | /// 203 | public static bool IsTelephone(this object thisValue) 204 | { 205 | if (thisValue == null) return false; 206 | return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}$"); 207 | 208 | } 209 | 210 | /// 211 | /// 是身份证? 212 | /// 213 | /// 214 | /// 215 | public static bool IsIDcard(this object thisValue) 216 | { 217 | if (thisValue == null) return false; 218 | return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$"); 219 | } 220 | 221 | /// 222 | /// 是传真? 223 | /// 224 | /// 225 | /// 226 | public static bool IsFax(this object thisValue) 227 | { 228 | if (thisValue == null) return false; 229 | return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$"); 230 | } 231 | 232 | /// 233 | /// 是适合正则匹配? 234 | /// 235 | /// 236 | /// 237 | /// 238 | public static bool IsMatch(this object thisValue, string pattern) 239 | { 240 | if (thisValue == null) return false; 241 | Regex reg = new Regex(pattern); 242 | return reg.IsMatch(thisValue.ToString()); 243 | } 244 | 245 | /// 246 | /// 是否是动态类型 247 | /// 248 | /// 249 | /// 250 | public static bool IsAnonymousType(this Type type) 251 | { 252 | string typeName = type.Name; 253 | return typeName.Contains("<>") && typeName.Contains("__") && typeName.Contains("AnonymousType"); 254 | } 255 | /// 256 | /// 是List类型 257 | /// 258 | /// 259 | /// 260 | public static bool IsCollectionsList(this string thisValue) 261 | { 262 | return (thisValue + "").StartsWith("System.Collections.Generic.List"); 263 | } 264 | /// 265 | /// 是string[]类型 266 | /// 267 | /// 268 | /// 269 | public static bool IsStringArray(this string thisValue) 270 | { 271 | return (thisValue + "").IsMatch(@"System\.[a-z,A-Z,0-9]+?\[\]"); 272 | } 273 | /// 274 | /// 是Enumerable 275 | /// 276 | /// 277 | /// 278 | public static bool IsEnumerable(this string thisValue) 279 | { 280 | return (thisValue + "").StartsWith("System.Linq.Enumerable"); 281 | } 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Queryable/Queryable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using MySql.Data.MySqlClient; 6 | using System.Linq.Expressions; 7 | 8 | namespace MySqlSugar 9 | { 10 | 11 | /// 12 | /// ** 描述:Queryable拉姆达查询对象 13 | /// ** 创始时间:2015-7-13 14 | /// ** 修改时间:- 15 | /// ** 作者:sunkaixuan 16 | /// ** 使用说明: 17 | /// 18 | public class Queryable 19 | { 20 | #region 临时变量 21 | /// 22 | /// T的名称 23 | /// 24 | internal string TName { get { return typeof(T).Name; } } 25 | /// 26 | /// 实体类型 27 | /// 28 | internal Type Type { get { return typeof(T); } } 29 | /// 30 | /// 数据接口 31 | /// 32 | public SqlSugarClient DB = null; 33 | /// 34 | /// Where临时数据 35 | /// 36 | internal List WhereValue = new List(); 37 | /// 38 | /// Skip临时数据 39 | /// 40 | internal int? Skip { get; set; } 41 | /// 42 | /// Take临时数据 43 | /// 44 | internal int? Take { get; set; } 45 | /// 46 | /// Order临时数据 47 | /// 48 | internal string OrderByValue { get; set; } 49 | /// 50 | /// Select临时数据 51 | /// 52 | internal string SelectValue { get; set; } 53 | /// 54 | /// SqlParameter临时数据 55 | /// 56 | internal List Params = new List(); 57 | /// 58 | /// 表名临时数据 59 | /// 60 | internal string TableName { get; set; } 61 | /// 62 | /// 分组查询临时数据 63 | /// 64 | internal string GroupByValue { get; set; } 65 | /// 66 | /// 条件索引临时数据 67 | /// 68 | internal int WhereIndex = 1; 69 | /// 70 | /// 联表查询临时数据 71 | /// 72 | internal List JoinTableValue = new List(); 73 | 74 | #endregion 75 | 76 | 77 | #region 公开函数 78 | /// 79 | /// 联表查询 80 | /// 81 | /// 联接的表对象 82 | /// 表达式 83 | /// Join的类型 84 | /// 85 | public Queryable JoinTable(Expression> expression, JoinType type = JoinType.Left) 86 | { 87 | return this.JoinTable(expression, type); 88 | } 89 | 90 | /// 91 | /// 联表查询 92 | /// 93 | /// 联接表的对象 94 | /// 联接表的对象 95 | /// 表达式 96 | /// Join的类型 97 | /// 98 | public Queryable JoinTable(Expression> expression, JoinType type = JoinType.Left) 99 | { 100 | return this.JoinTable(expression, type); 101 | } 102 | 103 | /// 104 | /// 条件筛选 105 | /// 106 | /// 表实体类型 107 | /// 表达式条件 108 | /// 109 | public Queryable Where(Expression> expression) 110 | { 111 | return this.Where(expression); 112 | } 113 | /// 114 | /// 条件筛选 115 | /// 116 | /// 表实体类型 117 | /// Where后面的Sql条件语句 (例如: id=@id ) 118 | /// 匿名参数 (例如:new{id=1,name="张三"}) 119 | /// 120 | public Queryable Where(string whereString, object whereObj = null) 121 | { 122 | return this.Where(whereString, whereObj); 123 | } 124 | 125 | /// 126 | /// 条件筛选 127 | /// 128 | /// 表实体类型 129 | /// 表实体类型 130 | /// 表达式条件 131 | /// 132 | public Queryable Where(Expression> expression) 133 | { 134 | return this.Where(expression); 135 | } 136 | 137 | /// 138 | /// 条件筛选 139 | /// 140 | /// 表实体类型 141 | /// 表实体类型 142 | /// 表实体类型 143 | /// 表达式条件 144 | /// 145 | public Queryable Where(Expression> expression) 146 | { 147 | return this.Where(expression); 148 | } 149 | 150 | /// 151 | /// 条件筛选 152 | /// 153 | /// 表实体类型 154 | /// 表实体类型 155 | /// 表实体类型 156 | /// 表实体类型 157 | /// 表达式条件 158 | /// 159 | public Queryable Where(Expression> expression) 160 | { 161 | return this.Where(expression); 162 | } 163 | 164 | /// 165 | /// 排序 166 | /// 167 | /// 表实体类型 168 | /// 例如 (s1,s2)=>s1.id,相当于 order by s1.id 169 | /// 排序类型 170 | /// 171 | public Queryable OrderBy(Expression> expression, OrderByType type = OrderByType.asc) 172 | { 173 | return this.OrderBy(expression, type); 174 | } 175 | 176 | /// 177 | /// 获取最大值 178 | /// 179 | /// 返回类型 180 | /// 列名 181 | /// 182 | public TResult Max(string maxField) 183 | { 184 | return this.Max(maxField); 185 | } 186 | 187 | /// 188 | /// 获取最小值 189 | /// 190 | /// 返回类型 191 | /// 列名 192 | /// 193 | public TResult Min(string minField) 194 | { 195 | return this.Min(minField); 196 | } 197 | 198 | /// 199 | /// 将源数据对象转换到新对象中 200 | /// 201 | /// 原数据实体类型 202 | /// 返回值的新实体类型 203 | /// 给新实体赋值的表达式 204 | /// 205 | public Queryable Select(Expression> expression) 206 | { 207 | return this.Select(expression); 208 | } 209 | 210 | /// 211 | /// 将源数据对象转换到新对象中 212 | /// 213 | /// 原数据实体类型 214 | /// 原数据实体类型 215 | /// 返回值的新实体类型 216 | /// 给新实体赋值的表达式 217 | /// 218 | public Queryable Select(Expression> expression) 219 | { 220 | return this.Select(expression); 221 | } 222 | 223 | /// 224 | /// 将源数据对象转换到新对象中 225 | /// 226 | /// 原数据实体类型 227 | /// 原数据实体类型 228 | /// 原数据实体类型 229 | /// 返回值的新实体类型 230 | /// 给新实体赋值的表达式 231 | /// 232 | public Queryable Select(Expression> expression) 233 | { 234 | return this.Select(expression); 235 | } 236 | 237 | /// 238 | /// 将源数据对象转换到新对象中 239 | /// 240 | /// 原数据实体类型 241 | /// 原数据实体类型 242 | /// 原数据实体类型 243 | /// 原数据实体类型 244 | /// 返回值的新实体类型 245 | /// 给新实体赋值的表达式 246 | /// 247 | public Queryable Select(Expression> expression) 248 | { 249 | return this.Select(expression); 250 | } 251 | 252 | /// 253 | /// 将源数据对象转换到新对象中 254 | /// 255 | /// 返回值的新实体类型 256 | /// 给新实体赋值的表达式 257 | /// 258 | public Queryable Select(Expression> expression) 259 | { 260 | return this.Select(expression); 261 | } 262 | 263 | /// 264 | /// 将源数据对象转换到新对象中 265 | /// 266 | /// 返回值的新实体类型 267 | /// 查询字符串(例如 id,name) 268 | /// 269 | public Queryable Select(string select) 270 | { 271 | return this.Select(select); 272 | } 273 | #endregion 274 | 275 | 276 | } 277 | } 278 | -------------------------------------------------------------------------------- /src/MySqlSugarForCore/Core/ResolveExpress/Method.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Linq.Expressions; 6 | using System.Collections; 7 | 8 | namespace MySqlSugar 9 | { 10 | //局部类:解析函数 11 | internal partial class ResolveExpress 12 | { 13 | /// 14 | /// 是否相等 15 | /// 16 | /// 17 | /// 18 | /// 19 | private string Equals(string methodName, MethodCallExpression mce) { 20 | MemberType leftType = MemberType.None; 21 | MemberType rightType = MemberType.None; 22 | var left = CreateSqlElements(mce.Object, ref leftType,true); 23 | var right = mce.Arguments[0].NodeType.IsIn(ExpressionType.Constant, ExpressionType.MemberAccess) ? CreateSqlElements(mce.Arguments[0], ref rightType, true) : Expression.Lambda(mce.Arguments[0]).Compile().DynamicInvoke().ObjToString(); 24 | Check.Exception(leftType == MemberType.Value, string.Format(ExpMethodError,methodName)); 25 | var oldLeft = AddParas(ref left,right); 26 | return string.Format("({0} = " + SqlSugarTool.ParSymbol + "{1})", oldLeft, left); 27 | } 28 | 29 | /// 30 | /// 拉姆达StartsWith函数处理 31 | /// 32 | /// 33 | /// 34 | /// 35 | /// 36 | private string StartsWith(string methodName, MethodCallExpression mce, bool isTure) 37 | { 38 | MemberType leftType = MemberType.None; 39 | MemberType rightType = MemberType.None; 40 | var left = CreateSqlElements(mce.Object, ref leftType,true); 41 | var right = mce.Arguments[0].NodeType.IsIn(ExpressionType.Constant, ExpressionType.MemberAccess) ? CreateSqlElements(mce.Arguments[0], ref rightType, true) : Expression.Lambda(mce.Arguments[0]).Compile().DynamicInvoke().ObjToString(); 42 | Check.Exception(leftType == MemberType.Value, string.Format(ExpMethodError, methodName)); 43 | var oldLeft = AddParas(ref left, right + '%'); 44 | return string.Format("({0} {1} LIKE " + SqlSugarTool.ParSymbol + "{2})", oldLeft, null, left); 45 | } 46 | 47 | /// 48 | /// 拉姆达EndWith函数处理 49 | /// 50 | /// 51 | /// 52 | /// 53 | /// 54 | private string EndWith(string methodName, MethodCallExpression mce, bool isTure) 55 | { 56 | MemberType leftType = MemberType.None; 57 | MemberType rightType = MemberType.None; 58 | var left = CreateSqlElements(mce.Object, ref leftType,true); 59 | var right = mce.Arguments[0].NodeType.IsIn(ExpressionType.Constant, ExpressionType.MemberAccess) ? CreateSqlElements(mce.Arguments[0], ref rightType, true) : Expression.Lambda(mce.Arguments[0]).Compile().DynamicInvoke().ObjToString(); 60 | Check.Exception(leftType == MemberType.Value, string.Format(ExpMethodError, methodName)); 61 | var oldLeft = AddParas(ref left, '%' + right); 62 | return string.Format("({0} {1} LIKE " + SqlSugarTool.ParSymbol + "{2})", oldLeft, null, left); 63 | } 64 | 65 | /// 66 | /// 拉姆达Contains函数处理 67 | /// 68 | /// 69 | /// 70 | /// 71 | /// 72 | private string Contains(string methodName, MethodCallExpression mce, bool isTure) 73 | { 74 | MemberType leftType = MemberType.None; 75 | MemberType rightType = MemberType.None; 76 | var left = CreateSqlElements(mce.Object, ref leftType,true); 77 | var right = mce.Arguments[0].NodeType.IsIn(ExpressionType.Constant, ExpressionType.MemberAccess) ? CreateSqlElements(mce.Arguments[0], ref rightType, true) : Expression.Lambda(mce.Arguments[0]).Compile().DynamicInvoke().ObjToString(); 78 | if (left.IsCollectionsList() || right.IsStringArray() || right.IsEnumerable()) 79 | { 80 | object containsValue = null; 81 | string fieldName = ""; 82 | if (left.IsCollectionsList()) 83 | { 84 | fieldName = right; 85 | MemberExpression mbx = ((MemberExpression)mce.Object); 86 | Expression exp = mce.Object; 87 | SetMemberValueToDynInv(ref exp, mbx, ref containsValue); 88 | 89 | } 90 | else 91 | { 92 | MemberExpression mbx = ((MemberExpression)mce.Arguments[0]); 93 | Expression exp = mce.Arguments[0]; 94 | SetMemberValueToDynInv(ref exp, mbx, ref containsValue); 95 | fieldName = CreateSqlElements(mce.Arguments[1], ref rightType,true); 96 | } 97 | List inArray = new List(); 98 | foreach (var item in (IEnumerable)containsValue) 99 | { 100 | inArray.Add(item.ObjToString()); 101 | } 102 | if (inArray.Count == 0) 103 | { 104 | return (" (1=2) "); 105 | } 106 | var inValue = inArray.ToArray().ToJoinSqlInVal(); 107 | return string.Format("({0} IN ({1}))", fieldName, inValue); 108 | } 109 | else if (mce.Arguments.Count == 2) { //两个值 110 | //object containsValue = null; 111 | //MemberExpression mbx = ((MemberExpression)mce.Arguments[0]); 112 | //Expression exp = mce.Arguments[0]; 113 | //SetMemberValueToDynInv(ref exp, mbx, ref containsValue); 114 | //var fieldName = CreateSqlElements(mce.Arguments[1], ref rightType); 115 | //return null; 116 | throw new SqlSugarException("请将数组提取成变量,不能直接写在表达式中。"); 117 | } 118 | else 119 | { 120 | Check.Exception(leftType == MemberType.Value, string.Format(ExpMethodError, methodName)); 121 | var oldLeft = AddParas(ref left, '%' + right + '%'); 122 | return string.Format("({0} {1} LIKE " + SqlSugarTool.ParSymbol + "{2})", oldLeft, null, left); 123 | } 124 | } 125 | 126 | /// 127 | /// 非空验证 128 | /// 129 | /// 130 | /// 131 | /// 132 | /// 133 | private string IsNullOrEmpty(string methodName, MethodCallExpression mce, bool isTure) 134 | { 135 | MemberType leftType = MemberType.None; 136 | MemberType rightType = MemberType.None; 137 | var isConstant = mce.Arguments.First().NodeType == ExpressionType.Constant; 138 | var left = CreateSqlElements(mce.Object, ref leftType,true); 139 | var right = mce.Arguments[0].NodeType.IsIn(ExpressionType.Constant, ExpressionType.MemberAccess) ? CreateSqlElements(mce.Arguments[0], ref rightType, true) : Expression.Lambda(mce.Arguments[0]).Compile().DynamicInvoke().ObjToString(); 140 | if (right == "null") 141 | { 142 | right = ""; 143 | } 144 | if (isConstant) 145 | { 146 | var oldLeft = AddParas(ref left, right); 147 | if (isTure) 148 | { 149 | return string.Format("(" + SqlSugarTool.ParSymbol + "{0} is null OR " + SqlSugarTool.ParSymbol + "{0}='' )", left); 150 | } 151 | else 152 | { 153 | return string.Format("(" + SqlSugarTool.ParSymbol + "{0} is not null AND " + SqlSugarTool.ParSymbol + "{0}<>'' )", left); 154 | } 155 | } 156 | else 157 | { 158 | if (isTure) 159 | { 160 | if (rightType == MemberType.Key) 161 | { 162 | return string.Format("({0} is null OR {0}='' )", right.ToSqlFilter()); 163 | } 164 | else 165 | { 166 | return string.Format("('{0}' is null OR '{0}'='' )", right.ToSqlFilter()); 167 | } 168 | } 169 | else 170 | { 171 | if (rightType == MemberType.Key) 172 | { 173 | return string.Format("({0} is not null AND {0}<>'' )", right.ToSqlFilter()); 174 | } 175 | else 176 | { 177 | 178 | return string.Format("('{0}' is not null AND '{0}'<>'' )", right.ToSqlFilter()); 179 | } 180 | } 181 | 182 | } 183 | } 184 | 185 | /// 186 | /// 参数函数 187 | /// 188 | /// 189 | /// 190 | /// 191 | /// 192 | private string ParMethodTo(string methodName, MethodCallExpression mce, ref MemberType type) 193 | { 194 | //参数函数 195 | MemberType rightType = MemberType.None; 196 | object right =null; 197 | if (mce.Arguments.IsValuable() && !methodName.IsIn("AddDays", "AddYears", "AddMonths")) 198 | { 199 | right = CreateSqlElements(mce.Arguments[0], ref rightType, true); 200 | } 201 | else { 202 | right = CreateSqlElements(mce.Object, ref rightType, true); 203 | } 204 | Check.Exception(rightType != MemberType.Value, string.Format(ExpMethodError2, methodName)); 205 | string value = string.Empty; 206 | if (mce.Arguments.IsValuable()) 207 | { 208 | value = right.ToString(); 209 | } 210 | else 211 | { 212 | value = MethodToString(methodName, mce, ref type); ; 213 | } 214 | if (methodName.IsIn("AddDays", "AddYears", "AddMonths")) 215 | { 216 | if (value.IsValuable()) 217 | { 218 | var parValue = CreateSqlElements(mce.Arguments[0], ref rightType, true).ObjToInt(); 219 | switch (methodName) 220 | { 221 | case "AddDays": value = value.ObjToDate().AddDays(parValue).ObjToString(); break; 222 | case "AddYears": value = value.ObjToDate().AddYears(parValue).ObjToString(); break; 223 | case "AddMonths": value = value.ObjToDate().AddMonths(parValue).ObjToString(); break; 224 | 225 | } 226 | } 227 | return value; 228 | } 229 | if (methodName == "ToDateTime" || methodName == "ObjToDate") 230 | { 231 | return Convert.ToDateTime(value).ToString(); 232 | } 233 | else if (methodName.StartsWith("ToInt")) 234 | { 235 | return Convert.ToInt32(value).ToString(); 236 | } 237 | else if (methodName.StartsWith("Trim")) 238 | { 239 | return (value.ObjToString()).Trim(); 240 | } 241 | else if (methodName.StartsWith("ObjTo")) 242 | { 243 | return value; 244 | } 245 | else if (methodName == "ToLower") { 246 | if (value == null) return value; 247 | else 248 | return value.ToLower(); 249 | } 250 | else if (methodName == "ToUpper") 251 | { 252 | if (value == null) return value; 253 | else 254 | return value.ToUpper(); 255 | } 256 | else 257 | { 258 | throw new SqlSugarException("不支持当前函数:" + methodName + "\r\n" + ResolveExpress.ExpToSqlError); 259 | } 260 | } 261 | 262 | /// 263 | /// 拉姆达ToString函数处理 264 | /// 265 | /// 266 | /// 267 | /// 268 | /// 269 | private string MethodToString(string methodName, MethodCallExpression mce, ref MemberType type) 270 | { 271 | return CreateSqlElements(mce.Object, ref type,true); 272 | } 273 | } 274 | } 275 | --------------------------------------------------------------------------------