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