diff --git a/src/Admin/ThingsGateway.Common/Extensions/ObjectExtensions.cs b/src/Admin/ThingsGateway.Common/Extensions/ObjectExtensions.cs index 715823a21..f3c496fd7 100644 --- a/src/Admin/ThingsGateway.Common/Extensions/ObjectExtensions.cs +++ b/src/Admin/ThingsGateway.Common/Extensions/ObjectExtensions.cs @@ -16,6 +16,8 @@ using System.Runtime.CompilerServices; using System.Text.Json; using System.Text.RegularExpressions; +using ThingsGateway.Extension; + namespace ThingsGateway.Common.Extension; /// /// 对象拓展类 @@ -48,113 +50,7 @@ public static class ObjectExtensions bool IsTheRawGenericType(Type type) => generic == (type.IsGenericType ? type.GetGenericTypeDefinition() : type); } - /// - /// 将 DateTimeOffset 转换成本地 DateTime - /// - /// - /// - public static DateTime ConvertToDateTime(this DateTimeOffset dateTime) - { - if (dateTime.Offset.Equals(TimeSpan.Zero)) - return dateTime.UtcDateTime; - if (dateTime.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(dateTime.DateTime))) - return dateTime.ToLocalTime().DateTime; - else - return dateTime.DateTime; - } - /// - /// 将 DateTimeOffset? 转换成本地 DateTime? - /// - /// - /// - public static DateTime? ConvertToDateTime(this DateTimeOffset? dateTime) - { - return dateTime.HasValue ? dateTime.Value.ConvertToDateTime() : null; - } - - /// - /// 将 DateTime 转换成 DateTimeOffset - /// - /// - /// - public static DateTimeOffset ConvertToDateTimeOffset(this DateTime dateTime) - { - return DateTime.SpecifyKind(dateTime, DateTimeKind.Local); - } - - /// - /// 将 DateTime? 转换成 DateTimeOffset? - /// - /// - /// - public static DateTimeOffset? ConvertToDateTimeOffset(this DateTime? dateTime) - { - return dateTime.HasValue ? dateTime.Value.ConvertToDateTimeOffset() : null; - } - - /// - /// 将流保存到本地磁盘 - /// - /// - /// - /// - public static void CopyToSave(this Stream stream, string path) - { - // 空检查 - if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(path)); - - using var fileStream = File.Create(path); - stream.CopyTo(fileStream); - } - - /// - /// 将字节数组保存到本地磁盘 - /// - /// - /// - /// - public static void CopyToSave(this byte[] bytes, string path) - { - using var stream = new MemoryStream(bytes); - stream.CopyToSave(path); - } - - /// - /// 将流保存到本地磁盘 - /// - /// - /// 需包含文件名完整路径 - /// - public static async Task CopyToSaveAsync(this Stream stream, string path) - { - // 空检查 - if (string.IsNullOrWhiteSpace(path)) - { - throw new ArgumentNullException(nameof(path)); - } - - // 文件名判断 - if (string.IsNullOrWhiteSpace(Path.GetFileName(path))) - { - throw new ArgumentException("The parameter of parameter must include the complete file name."); - } - - using var fileStream = File.Create(path); - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - } - - /// - /// 将字节数组保存到本地磁盘 - /// - /// - /// - /// - public static async Task CopyToSaveAsync(this byte[] bytes, string path) - { - using var stream = new MemoryStream(bytes); - await stream.CopyToSaveAsync(path).ConfigureAwait(false); - } /// /// 合并两个字典 diff --git a/src/Admin/ThingsGateway.Furion/App/Extensions/HostBuilderExtensions.cs b/src/Admin/ThingsGateway.Furion/App/Extensions/HostBuilderExtensions.cs index f413ade13..0e65d02bd 100644 --- a/src/Admin/ThingsGateway.Furion/App/Extensions/HostBuilderExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/App/Extensions/HostBuilderExtensions.cs @@ -12,7 +12,7 @@ using Microsoft.AspNetCore.Hosting; using ThingsGateway; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Reflection; namespace Microsoft.Extensions.Hosting; diff --git a/src/Admin/ThingsGateway.Furion/App/Extensions/ObjectExtensions.cs b/src/Admin/ThingsGateway.Furion/App/Extensions/ObjectExtensions.cs index 153d6ddd5..cdf2150e3 100644 --- a/src/Admin/ThingsGateway.Furion/App/Extensions/ObjectExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/App/Extensions/ObjectExtensions.cs @@ -20,7 +20,7 @@ using System.Text.RegularExpressions; using ThingsGateway.NewLife; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 对象拓展类 @@ -28,70 +28,10 @@ namespace ThingsGateway.Extensions; [SuppressSniffer] public static class ObjectExtensions { - /// - /// 将 DateTimeOffset 转换成本地 DateTime - /// - /// - /// - public static DateTime ConvertToDateTime(this DateTimeOffset dateTime) - { - if (dateTime.Offset.Equals(TimeSpan.Zero)) - return dateTime.UtcDateTime; - if (dateTime.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(dateTime.DateTime))) - return dateTime.ToLocalTime().DateTime; - else - return dateTime.DateTime; - } - /// - /// 将 DateTimeOffset? 转换成本地 DateTime? - /// - /// - /// - public static DateTime? ConvertToDateTime(this DateTimeOffset? dateTime) - { - return dateTime.HasValue ? dateTime.Value.ConvertToDateTime() : null; - } - /// - /// 将 DateTime 转换成 DateTimeOffset - /// - /// - /// - public static DateTimeOffset ConvertToDateTimeOffset(this DateTime dateTime) - { - return DateTime.SpecifyKind(dateTime, DateTimeKind.Local); - } - /// - /// 将 DateTime? 转换成 DateTimeOffset? - /// - /// - /// - public static DateTimeOffset? ConvertToDateTimeOffset(this DateTime? dateTime) - { - return dateTime.HasValue ? dateTime.Value.ConvertToDateTimeOffset() : null; - } - /// - /// 将时间戳转换为 DateTime - /// - /// - /// - internal static DateTime ConvertToDateTime(this long timestamp) - { - var timeStampDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - var digitCount = (int)Math.Floor(Math.Log10(timestamp) + 1); - - if (digitCount != 13 && digitCount != 10) - { - throw new ArgumentException("Data is not a valid timestamp format."); - } - - return (digitCount == 13 - ? timeStampDateTime.AddMilliseconds(timestamp) // 13 位时间戳 - : timeStampDateTime.AddSeconds(timestamp)).ToLocalTime(); // 10 位时间戳 - } /// /// 将 IFormFile 转换成 byte[] diff --git a/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/FlexibleArrayModelBinder.cs b/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/FlexibleArrayModelBinder.cs index 1c6ef3e8b..0373e8165 100644 --- a/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/FlexibleArrayModelBinder.cs +++ b/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/FlexibleArrayModelBinder.cs @@ -11,7 +11,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.AspNetCore; diff --git a/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/TimestampToDateTimeModelBinder.cs b/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/TimestampToDateTimeModelBinder.cs index df0f7adb0..d53dc06f1 100644 --- a/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/TimestampToDateTimeModelBinder.cs +++ b/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Binders/TimestampToDateTimeModelBinder.cs @@ -11,7 +11,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.AspNetCore; diff --git a/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Converts/DateTimeOffsetModelConvertBinder.cs b/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Converts/DateTimeOffsetModelConvertBinder.cs index ec03efa45..295a3c03b 100644 --- a/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Converts/DateTimeOffsetModelConvertBinder.cs +++ b/src/Admin/ThingsGateway.Furion/AspNetCore/ModelBinders/Converts/DateTimeOffsetModelConvertBinder.cs @@ -12,7 +12,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.AspNetCore; diff --git a/src/Admin/ThingsGateway.Furion/ConfigurableOptions/Extensions/ConfigurableOptionsServiceCollectionExtensions.cs b/src/Admin/ThingsGateway.Furion/ConfigurableOptions/Extensions/ConfigurableOptionsServiceCollectionExtensions.cs index b9cd5eddd..e27920ba8 100644 --- a/src/Admin/ThingsGateway.Furion/ConfigurableOptions/Extensions/ConfigurableOptionsServiceCollectionExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/ConfigurableOptions/Extensions/ConfigurableOptionsServiceCollectionExtensions.cs @@ -18,7 +18,7 @@ using System.Reflection; using ThingsGateway; using ThingsGateway.ConfigurableOptions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace Microsoft.Extensions.DependencyInjection; diff --git a/src/Admin/ThingsGateway.Furion/DataValidation/Validators/DataValidator.cs b/src/Admin/ThingsGateway.Furion/DataValidation/Validators/DataValidator.cs index da1afcc41..6d0432316 100644 --- a/src/Admin/ThingsGateway.Furion/DataValidation/Validators/DataValidator.cs +++ b/src/Admin/ThingsGateway.Furion/DataValidation/Validators/DataValidator.cs @@ -16,7 +16,7 @@ using System.ComponentModel.DataAnnotations; using System.Reflection; using System.Text.RegularExpressions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Templates.Extensions; namespace ThingsGateway.DataValidation; diff --git a/src/Admin/ThingsGateway.Furion/DynamicApiController/Conventions/DynamicApiControllerApplicationModelConvention.cs b/src/Admin/ThingsGateway.Furion/DynamicApiController/Conventions/DynamicApiControllerApplicationModelConvention.cs index c153badb1..a33cb5cf1 100644 --- a/src/Admin/ThingsGateway.Furion/DynamicApiController/Conventions/DynamicApiControllerApplicationModelConvention.cs +++ b/src/Admin/ThingsGateway.Furion/DynamicApiController/Conventions/DynamicApiControllerApplicationModelConvention.cs @@ -21,7 +21,7 @@ using System.Collections.Concurrent; using System.Reflection; using System.Text.RegularExpressions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.UnifyResult; namespace ThingsGateway.DynamicApiController; diff --git a/src/Admin/ThingsGateway.Furion/FriendlyException/Oops.cs b/src/Admin/ThingsGateway.Furion/FriendlyException/Oops.cs index 20c0f69a6..5d7a1ee9f 100644 --- a/src/Admin/ThingsGateway.Furion/FriendlyException/Oops.cs +++ b/src/Admin/ThingsGateway.Furion/FriendlyException/Oops.cs @@ -17,7 +17,7 @@ using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Templates.Extensions; namespace ThingsGateway.FriendlyException; diff --git a/src/Admin/ThingsGateway.Furion/InstantMessaging/Extensions/IEndpointRouteBuilderExtensions.cs b/src/Admin/ThingsGateway.Furion/InstantMessaging/Extensions/IEndpointRouteBuilderExtensions.cs index a95859c3d..8cc650962 100644 --- a/src/Admin/ThingsGateway.Furion/InstantMessaging/Extensions/IEndpointRouteBuilderExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/InstantMessaging/Extensions/IEndpointRouteBuilderExtensions.cs @@ -16,7 +16,7 @@ using Microsoft.AspNetCore.SignalR; using System.Reflection; using ThingsGateway; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.InstantMessaging; namespace Microsoft.AspNetCore.Builder; diff --git a/src/Admin/ThingsGateway.Furion/Logging/Extensions/LogContextExtensions.cs b/src/Admin/ThingsGateway.Furion/Logging/Extensions/LogContextExtensions.cs index a8807062b..dc79dff84 100644 --- a/src/Admin/ThingsGateway.Furion/Logging/Extensions/LogContextExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/Logging/Extensions/LogContextExtensions.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Logging; diff --git a/src/Admin/ThingsGateway.Furion/Logging/Implantations/Monitors/LoggingMonitorAttribute.cs b/src/Admin/ThingsGateway.Furion/Logging/Implantations/Monitors/LoggingMonitorAttribute.cs index 4cdfd75fe..6bd3c1f9a 100644 --- a/src/Admin/ThingsGateway.Furion/Logging/Implantations/Monitors/LoggingMonitorAttribute.cs +++ b/src/Admin/ThingsGateway.Furion/Logging/Implantations/Monitors/LoggingMonitorAttribute.cs @@ -36,7 +36,7 @@ using System.Text.Json; using ThingsGateway; using ThingsGateway.DataValidation; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.FriendlyException; using ThingsGateway.JsonSerialization; using ThingsGateway.Logging; diff --git a/src/Admin/ThingsGateway.Furion/Options/Extensions/OptionsBuilderExtensions.cs b/src/Admin/ThingsGateway.Furion/Options/Extensions/OptionsBuilderExtensions.cs index 24ecee354..dc85b89b7 100644 --- a/src/Admin/ThingsGateway.Furion/Options/Extensions/OptionsBuilderExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/Options/Extensions/OptionsBuilderExtensions.cs @@ -16,7 +16,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using System.Linq.Expressions; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Options; namespace Microsoft.Extensions.Options; diff --git a/src/Admin/ThingsGateway.Furion/SpecificationDocument/Builders/SpecificationDocumentBuilder.cs b/src/Admin/ThingsGateway.Furion/SpecificationDocument/Builders/SpecificationDocumentBuilder.cs index 3879935fd..917b2cb80 100644 --- a/src/Admin/ThingsGateway.Furion/SpecificationDocument/Builders/SpecificationDocumentBuilder.cs +++ b/src/Admin/ThingsGateway.Furion/SpecificationDocument/Builders/SpecificationDocumentBuilder.cs @@ -31,7 +31,7 @@ using System.Xml.Linq; using System.Xml.XPath; using ThingsGateway.DynamicApiController; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Reflection; namespace ThingsGateway.SpecificationDocument; diff --git a/src/Admin/ThingsGateway.Furion/SpecificationDocument/Filters/EnumSchemaFilter.cs b/src/Admin/ThingsGateway.Furion/SpecificationDocument/Filters/EnumSchemaFilter.cs index 524bdff89..feb71f925 100644 --- a/src/Admin/ThingsGateway.Furion/SpecificationDocument/Filters/EnumSchemaFilter.cs +++ b/src/Admin/ThingsGateway.Furion/SpecificationDocument/Filters/EnumSchemaFilter.cs @@ -20,7 +20,7 @@ using System.Reflection; using System.Text; using System.Text.RegularExpressions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.SpecificationDocument; diff --git a/src/Admin/ThingsGateway.Furion/Templates/Extensions/StringRenderExtensions.cs b/src/Admin/ThingsGateway.Furion/Templates/Extensions/StringRenderExtensions.cs index afa5bbb06..df44693b7 100644 --- a/src/Admin/ThingsGateway.Furion/Templates/Extensions/StringRenderExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/Templates/Extensions/StringRenderExtensions.cs @@ -11,7 +11,7 @@ using System.Text.RegularExpressions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Templates.Extensions; diff --git a/src/Admin/ThingsGateway.Furion/UnifyResult/Attributes/UnifyResultAttribute.cs b/src/Admin/ThingsGateway.Furion/UnifyResult/Attributes/UnifyResultAttribute.cs index 575193d63..9f5bfee89 100644 --- a/src/Admin/ThingsGateway.Furion/UnifyResult/Attributes/UnifyResultAttribute.cs +++ b/src/Admin/ThingsGateway.Furion/UnifyResult/Attributes/UnifyResultAttribute.cs @@ -13,7 +13,7 @@ using Microsoft.AspNetCore.Http; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.UnifyResult; namespace Microsoft.AspNetCore.Mvc; diff --git a/src/Admin/ThingsGateway.Furion/UnifyResult/UnifyContext.cs b/src/Admin/ThingsGateway.Furion/UnifyResult/UnifyContext.cs index 35dc86134..91455c5cc 100644 --- a/src/Admin/ThingsGateway.Furion/UnifyResult/UnifyContext.cs +++ b/src/Admin/ThingsGateway.Furion/UnifyResult/UnifyContext.cs @@ -22,7 +22,7 @@ using Microsoft.Extensions.Options; using System.Collections.Concurrent; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.FriendlyException; namespace ThingsGateway.UnifyResult; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Converters/Json/StringJsonConverter.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Converters/Json/StringJsonConverter.cs index 3efcc9512..f23949756 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Converters/Json/StringJsonConverter.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Converters/Json/StringJsonConverter.cs @@ -12,7 +12,7 @@ using System.Text.Json; using System.Text.Json.Serialization; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Converters.Json; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/AssemblyExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/AssemblyExtensions.cs index 06a06f88c..7f17576ce 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/AssemblyExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/AssemblyExtensions.cs @@ -11,7 +11,7 @@ using System.Reflection; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ConcurrentDictionaryExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ConcurrentDictionaryExtensions.cs index 7194f9baf..1e4d047b2 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ConcurrentDictionaryExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ConcurrentDictionaryExtensions.cs @@ -11,7 +11,7 @@ using System.Collections.Concurrent; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/CoreServiceCollectionExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/CoreServiceCollectionExtensions.cs index 055275c6b..ab1606b02 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/CoreServiceCollectionExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/CoreServiceCollectionExtensions.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Hosting; using System.Reflection; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 核心模块 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DataTableAndSetExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DataTableAndSetExtensions.cs index a766f4466..2bfff3c24 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DataTableAndSetExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DataTableAndSetExtensions.cs @@ -11,7 +11,7 @@ using System.Data; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DelegateExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DelegateExtensions.cs index c992e807c..f0b58103c 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DelegateExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/DelegateExtensions.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 委托拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EnumExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EnumExtensions.cs index df01e6e6a..d7253cf0b 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EnumExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EnumExtensions.cs @@ -12,7 +12,7 @@ using System.ComponentModel; using System.Reflection; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 枚举拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EventHandlerExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EventHandlerExtensions.cs index eac8a4445..dbc214389 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EventHandlerExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/EventHandlerExtensions.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ICollectionExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ICollectionExtensions.cs index c2109943f..9c2f74f04 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ICollectionExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/ICollectionExtensions.cs @@ -11,7 +11,7 @@ using System.Diagnostics.CodeAnalysis; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IDictionaryExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IDictionaryExtensions.cs index f1322e4fe..8115ec724 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IDictionaryExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IDictionaryExtensions.cs @@ -11,7 +11,7 @@ using System.Collections.Concurrent; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IEnumerableExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IEnumerableExtensions.cs index 7d76613f5..64a5b1b2b 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IEnumerableExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/IEnumerableExtensions.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/JsonExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/JsonExtensions.cs index 86ce33b83..ba9b41a93 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/JsonExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/JsonExtensions.cs @@ -18,7 +18,7 @@ using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// System.Text.Json 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/LinqExpressionExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/LinqExpressionExtensions.cs index 3d53182b0..87afc524c 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/LinqExpressionExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/LinqExpressionExtensions.cs @@ -12,7 +12,7 @@ using System.Linq.Expressions; using System.Reflection; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/MethodInfoExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/MethodInfoExtensions.cs index 27d02fd5d..96e4a1709 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/MethodInfoExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/MethodInfoExtensions.cs @@ -12,7 +12,7 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/NumberExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/NumberExtensions.cs index b90f1c56b..5e316be0a 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/NumberExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/NumberExtensions.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 数值类型拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/StringExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/StringExtensions.cs index 0aba62fa3..165718542 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/StringExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/StringExtensions.cs @@ -17,7 +17,7 @@ using System.Reflection; using System.Text; using System.Text.RegularExpressions; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/TypeExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/TypeExtensions.cs index 4a2ebc1ca..5206d446b 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/TypeExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/TypeExtensions.cs @@ -15,7 +15,7 @@ using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/Utf8JsonReaderExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/Utf8JsonReaderExtensions.cs index d2871015f..92ae5e33d 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/Utf8JsonReaderExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/Utf8JsonReaderExtensions.cs @@ -13,7 +13,7 @@ using System.Buffers; using System.Text; using System.Text.Json; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/V5_ObjectExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/V5_ObjectExtensions.cs index 0fd196f7d..5a1bee2e9 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/V5_ObjectExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Extensions/V5_ObjectExtensions.cs @@ -16,7 +16,7 @@ using System.Text.Json; using ThingsGateway.Utilities; -namespace ThingsGateway.Extensions; +namespace ThingsGateway.Extension; /// /// 拓展类 diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertyGetter.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertyGetter.cs index 34c0c4729..2eeb408f1 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertyGetter.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertyGetter.cs @@ -13,7 +13,7 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Reflection; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertySetter.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertySetter.cs index 1ca8f0ee2..b39876e22 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertySetter.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Reflection/ObjectPropertySetter.cs @@ -13,7 +13,7 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Reflection; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/FileUtility.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/FileUtility.cs index 0efa8cf38..4e0b69095 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/FileUtility.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/FileUtility.cs @@ -11,7 +11,7 @@ using System.Diagnostics.CodeAnalysis; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Utilities; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/StringUtility.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/StringUtility.cs index 67ced3b8a..ac92e02fe 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/StringUtility.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Core/Utilities/StringUtility.cs @@ -11,7 +11,7 @@ using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Utilities; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpContextForwardBuilder.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpContextForwardBuilder.cs index ee95d38eb..d1fb51ad0 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpContextForwardBuilder.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpContextForwardBuilder.cs @@ -18,7 +18,7 @@ using Microsoft.Net.Http.Headers; using System.Net.Mime; using ThingsGateway.AspNetCore.Extensions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpFileUploadBuilder.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpFileUploadBuilder.cs index 3c46f2cb1..37c34e2c7 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpFileUploadBuilder.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpFileUploadBuilder.cs @@ -12,7 +12,7 @@ using System.Net.Http.Headers; using System.Threading.Channels; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpMultipartFormDataBuilder.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpMultipartFormDataBuilder.cs index 2244f565f..9b53b1b81 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpMultipartFormDataBuilder.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpMultipartFormDataBuilder.cs @@ -16,7 +16,7 @@ using System.Text; using System.Text.Json; using System.Threading.Channels; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRemoteBuilder.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRemoteBuilder.cs index 889dd5690..e9949646b 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRemoteBuilder.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRemoteBuilder.cs @@ -16,7 +16,7 @@ using Microsoft.Extensions.Logging; using System.Reflection; using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.Methods.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.Methods.cs index 21ad3719f..e9c00abfa 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.Methods.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.Methods.cs @@ -17,7 +17,7 @@ using System.Net.Mime; using System.Text; using System.Text.Json; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.cs index 38068b3ff..95e305044 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Builders/HttpRequestBuilder.cs @@ -16,7 +16,7 @@ using System.Globalization; using System.Net.Http.Headers; using System.Net.Mime; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using CacheControlHeaderValue = System.Net.Http.Headers.CacheControlHeaderValue; using StringWithQualityHeaderValue = System.Net.Http.Headers.StringWithQualityHeaderValue; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Builders/HttpDeclarativeBuilder.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Builders/HttpDeclarativeBuilder.cs index 5f83127b3..24d1ceb73 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Builders/HttpDeclarativeBuilder.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Builders/HttpDeclarativeBuilder.cs @@ -14,7 +14,7 @@ using System.Collections.Concurrent; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/BodyDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/BodyDeclarativeExtractor.cs index 376765e4b..a3dac7e02 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/BodyDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/BodyDeclarativeExtractor.cs @@ -12,7 +12,7 @@ using System.Net.Mime; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/CookieDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/CookieDeclarativeExtractor.cs index 8ff5319b7..874bdd0d2 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/CookieDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/CookieDeclarativeExtractor.cs @@ -11,7 +11,7 @@ using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/HeaderDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/HeaderDeclarativeExtractor.cs index f53325f6f..c076fe799 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/HeaderDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/HeaderDeclarativeExtractor.cs @@ -11,7 +11,7 @@ using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/MultipartDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/MultipartDeclarativeExtractor.cs index e28539bdf..80ba8b558 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/MultipartDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/MultipartDeclarativeExtractor.cs @@ -14,7 +14,7 @@ using System.Net.Mime; using System.Reflection; using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PathDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PathDeclarativeExtractor.cs index 48d22588b..2bc56f748 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PathDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PathDeclarativeExtractor.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PropertyDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PropertyDeclarativeExtractor.cs index 60107441a..507e2c4fe 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PropertyDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/PropertyDeclarativeExtractor.cs @@ -11,7 +11,7 @@ using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/QueryDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/QueryDeclarativeExtractor.cs index dbe02c370..241058e56 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/QueryDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/QueryDeclarativeExtractor.cs @@ -11,7 +11,7 @@ using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/ValidationDeclarativeExtractor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/ValidationDeclarativeExtractor.cs index 78968e975..d395618b0 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/ValidationDeclarativeExtractor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/Extractors/ValidationDeclarativeExtractor.cs @@ -12,7 +12,7 @@ using System.ComponentModel.DataAnnotations; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/HttpDeclarativeExtractorContext.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/HttpDeclarativeExtractorContext.cs index f61dd94b8..14c80b31f 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/HttpDeclarativeExtractorContext.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Declarative/HttpDeclarativeExtractorContext.cs @@ -12,7 +12,7 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpContextExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpContextExtensions.cs index b76ffd20f..3b434c28a 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpContextExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpContextExtensions.cs @@ -14,7 +14,7 @@ using Microsoft.Extensions.DependencyInjection; using System.Net.Http.Headers; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote.Extensions; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpRemoteExtensions.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpRemoteExtensions.cs index 4bed5356d..1d8923647 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpRemoteExtensions.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Extensions/HttpRemoteExtensions.cs @@ -18,7 +18,7 @@ using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; using StringWithQualityHeaderValue = System.Net.Http.Headers.StringWithQualityHeaderValue; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentConverterFactory.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentConverterFactory.cs index eb5e11dd2..2c59bd4d1 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentConverterFactory.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentConverterFactory.cs @@ -11,7 +11,7 @@ using Microsoft.Extensions.DependencyInjection; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentProcessorFactory.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentProcessorFactory.cs index fe40efbef..039bf6922 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentProcessorFactory.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Factories/HttpContentProcessorFactory.cs @@ -11,7 +11,7 @@ using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Filters/ForwardAttribute.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Filters/ForwardAttribute.cs index a7519648c..664370cf5 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Filters/ForwardAttribute.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Filters/ForwardAttribute.cs @@ -14,7 +14,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.HttpRemote.Extensions; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Formatters/UrlParameterFormatter.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Formatters/UrlParameterFormatter.cs index d39852164..fefb2d4aa 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Formatters/UrlParameterFormatter.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Formatters/UrlParameterFormatter.cs @@ -11,7 +11,7 @@ using System.Globalization; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileDownloadManager.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileDownloadManager.cs index 21e50fa0b..97685f877 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileDownloadManager.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileDownloadManager.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Options; using System.Diagnostics; using System.Threading.Channels; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileUploadManager.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileUploadManager.cs index 496408a57..495c1fb3e 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileUploadManager.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/FileUploadManager.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Options; using System.Diagnostics; using System.Threading.Channels; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/LongPollingManager.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/LongPollingManager.cs index 457902943..289e10b24 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/LongPollingManager.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/LongPollingManager.cs @@ -14,7 +14,7 @@ using Microsoft.Extensions.Options; using System.Threading.Channels; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/ServerSentEventsManager.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/ServerSentEventsManager.cs index 2ee02d102..2163564f9 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/ServerSentEventsManager.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Managers/ServerSentEventsManager.cs @@ -16,7 +16,7 @@ using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading.Channels; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Models/FileTransferProgress.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Models/FileTransferProgress.cs index 65d479679..6f34940b9 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Models/FileTransferProgress.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Models/FileTransferProgress.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Utilities; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/FormUrlEncodedContentProcessor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/FormUrlEncodedContentProcessor.cs index 8c49caaa5..e30e2d98f 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/FormUrlEncodedContentProcessor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/FormUrlEncodedContentProcessor.cs @@ -14,7 +14,7 @@ using System.Net.Http.Headers; using System.Net.Mime; using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MessagePackContentProcessor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MessagePackContentProcessor.cs index 9f1cc783f..1935c0f0b 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MessagePackContentProcessor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MessagePackContentProcessor.cs @@ -14,7 +14,7 @@ using System.Net.Http.Headers; using System.Reflection; using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MultipartFormDataContentProcessor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MultipartFormDataContentProcessor.cs index bd3cef318..e0758eb12 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MultipartFormDataContentProcessor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/MultipartFormDataContentProcessor.cs @@ -12,7 +12,7 @@ using System.Net.Mime; using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentForFormUrlEncodedContentProcessor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentForFormUrlEncodedContentProcessor.cs index 3360054fb..a251cefbf 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentForFormUrlEncodedContentProcessor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentForFormUrlEncodedContentProcessor.cs @@ -13,7 +13,7 @@ using System.Globalization; using System.Net.Http.Headers; using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentProcessor.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentProcessor.cs index 2edf4cdea..c1ab3cbcd 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentProcessor.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Processors/StringContentProcessor.cs @@ -20,7 +20,7 @@ using System.Text; using System.Text.Json; using System.Text.Json.Nodes; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Services/HttpRemoteService.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Services/HttpRemoteService.cs index a16b8fceb..5ca7eb3c4 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Services/HttpRemoteService.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/Services/HttpRemoteService.cs @@ -18,7 +18,7 @@ using System.Net; using System.Reflection; using System.Text.RegularExpressions; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.Events.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.Events.cs index 0a2e0ee08..b3e3ff48c 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.Events.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.Events.cs @@ -9,7 +9,7 @@ // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.cs index 3c2162200..2bd819439 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/HttpRemote/WebSocket/WebSocketClient.cs @@ -12,7 +12,7 @@ using System.Net.WebSockets; using System.Text; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.HttpRemote; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Binders/ClayBinder.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Binders/ClayBinder.cs index b5019c6cc..a59f35495 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Binders/ClayBinder.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Binders/ClayBinder.cs @@ -19,7 +19,7 @@ using System.Net.Mime; using System.Reflection; using System.Web; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Shapeless; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Exports.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Exports.cs index 0dcc318db..c915baf6c 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Exports.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Exports.cs @@ -17,7 +17,7 @@ using System.Text.Json.Nodes; using System.Xml; using System.Xml.Linq; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Shapeless; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Override.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Override.cs index 6e32b4f96..5245644b8 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Override.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.Override.cs @@ -13,7 +13,7 @@ using System.Dynamic; using System.Reflection; using System.Text.Json; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; using ThingsGateway.Shapeless.Extensions; using Binder = Microsoft.CSharp.RuntimeBinder.Binder; diff --git a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.cs b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.cs index e4e6900a5..9f3fa37ec 100644 --- a/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.cs +++ b/src/Admin/ThingsGateway.Furion/V5_Experience/Shapeless/Clay/Clay.cs @@ -15,7 +15,7 @@ using System.Dynamic; using System.Text.Json; using System.Text.Json.Nodes; -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.Shapeless; diff --git a/src/Admin/ThingsGateway.NewLife.X/Extension/DateExtensions.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/DateExtensions.cs index 6bff46f59..e29c40a25 100644 --- a/src/Admin/ThingsGateway.NewLife.X/Extension/DateExtensions.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/DateExtensions.cs @@ -155,7 +155,7 @@ public static class DateExtensions /// /// /// - internal static DateTime ConvertToDateTime(this long timestamp) + public static DateTime ConvertToDateTime(this long timestamp) { var timeStampDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var digitCount = (int)Math.Floor(Math.Log10(timestamp) + 1); @@ -169,4 +169,5 @@ public static class DateExtensions ? timeStampDateTime.AddMilliseconds(timestamp) // 13 位时间戳 : timeStampDateTime.AddSeconds(timestamp)).ToLocalTime(); // 10 位时间戳 } + } diff --git a/src/Admin/ThingsGateway.Furion/JsonSerialization/Internal/Penetrates.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/Internal/Penetrates.cs similarity index 95% rename from src/Admin/ThingsGateway.Furion/JsonSerialization/Internal/Penetrates.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/Internal/Penetrates.cs index 78db18d09..54c96a788 100644 --- a/src/Admin/ThingsGateway.Furion/JsonSerialization/Internal/Penetrates.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/Internal/Penetrates.cs @@ -8,13 +8,14 @@ // 项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。 // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ - using Newtonsoft.Json; using Newtonsoft.Json.Linq; +#if NET6_0_OR_GREATER using System.Text.Json; +#endif -using ThingsGateway.Extensions; +using ThingsGateway.Extension; namespace ThingsGateway.JsonSerialization; @@ -23,6 +24,7 @@ namespace ThingsGateway.JsonSerialization; /// internal static class Penetrates { +#if NET6_0_OR_GREATER /// /// 转换 /// @@ -35,7 +37,6 @@ internal static class Penetrates { return longValue.ConvertToDateTime(); } - var stringValue = reader.GetString(); // 处理时间戳自动转换 @@ -46,6 +47,9 @@ internal static class Penetrates return Convert.ToDateTime(stringValue); } +#endif + + /// /// 转换 @@ -69,4 +73,6 @@ internal static class Penetrates return Convert.ToDateTime(stringValue); } -} \ No newline at end of file + +} + diff --git a/src/Admin/ThingsGateway.NewLife.X/Extension/LinqExtensions.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/LinqExtensions.cs index 7aab500bc..e7ae21e10 100644 --- a/src/Admin/ThingsGateway.NewLife.X/Extension/LinqExtensions.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/LinqExtensions.cs @@ -53,12 +53,16 @@ public static class LinqExtensions /// public static void RemoveWhere(this ICollection @this, Func @where) { - foreach (var obj in @this.Where(where).ToList()) + var del = new List(); + foreach (var obj in @this.Where(where)) + { + del.Add(obj); + } + foreach (var obj in del) { @this.Remove(obj); } } - /// public static IEnumerable WhereIf(this IEnumerable thisValue, bool isOk, Func predicate) { diff --git a/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftEncodingConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftEncodingConverter.cs new file mode 100644 index 000000000..d1e80ec75 --- /dev/null +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftEncodingConverter.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// 此代码版权声明为全文件覆盖,如有原作者特别声明,会在下方手动补充 +// 此代码版权(除特别声明外的代码)归作者本人Diego所有 +// 源代码使用协议遵循本仓库的开源协议及附加协议 +// Gitee源代码仓库:https://gitee.com/diego2098/ThingsGateway +// Github源代码仓库:https://github.com/kimdiego2098/ThingsGateway +// 使用文档:https://thingsgateway.cn/ +// QQ群:605534569 +//------------------------------------------------------------------------------ + +using Newtonsoft.Json; + +using System.Text; + +namespace ThingsGateway.Foundation; + + +/// +public class NewtonsoftEncodingConverter : Newtonsoft.Json.JsonConverter +{ + /// + public override Encoding? ReadJson(JsonReader reader, Type objectType, Encoding? existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer) + { + // 从 JSON 字符串中读取编码名称,并创建相应的 Encoding 对象 + string? encodingName = reader.Value as string; + return Encoding.GetEncoding(encodingName ?? Encoding.UTF8.WebName); + } + + /// + public override void WriteJson(JsonWriter writer, Encoding? value, Newtonsoft.Json.JsonSerializer serializer) + { + writer.WriteValue(value.WebName); + } +} diff --git a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonDateOnlyJsonConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonDateOnlyJsonConverter.cs similarity index 99% rename from src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonDateOnlyJsonConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonDateOnlyJsonConverter.cs index 16c201386..f8a013478 100644 --- a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonDateOnlyJsonConverter.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonDateOnlyJsonConverter.cs @@ -8,6 +8,7 @@ // 项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。 // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ +#if NET6_0_OR_GREATER using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -17,7 +18,6 @@ namespace ThingsGateway.JsonSerialization; /// /// DateOnly 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonDateOnlyJsonConverter : JsonConverter { /// @@ -72,7 +72,6 @@ public class NewtonsoftJsonDateOnlyJsonConverter : JsonConverter /// /// DateOnly? 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonNullableDateOnlyJsonConverter : JsonConverter { /// @@ -123,4 +122,6 @@ public class NewtonsoftJsonNullableDateOnlyJsonConverter : JsonConverter /// DateTime 类型序列化 /// -[SuppressSniffer] + public class NewtonsoftJsonDateTimeJsonConverter : JsonConverter { /// @@ -90,7 +90,7 @@ public class NewtonsoftJsonDateTimeJsonConverter : JsonConverter /// /// DateTime 类型序列化 /// -[SuppressSniffer] + public class NewtonsoftNullableJsonDateTimeJsonConverter : JsonConverter { /// diff --git a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonDateTimeOffsetJsonConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonDateTimeOffsetJsonConverter.cs similarity index 99% rename from src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonDateTimeOffsetJsonConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonDateTimeOffsetJsonConverter.cs index 57287cfd3..e0f4e016d 100644 --- a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonDateTimeOffsetJsonConverter.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonDateTimeOffsetJsonConverter.cs @@ -16,7 +16,6 @@ namespace ThingsGateway.JsonSerialization; /// /// DateTimeOffset 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonDateTimeOffsetJsonConverter : JsonConverter { /// @@ -90,7 +89,6 @@ public class NewtonsoftJsonDateTimeOffsetJsonConverter : JsonConverter /// DateTimeOffset 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonNullableDateTimeOffsetJsonConverter : JsonConverter { /// diff --git a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonJsonObjectJsonConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonJsonObjectJsonConverter.cs similarity index 98% rename from src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonJsonObjectJsonConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonJsonObjectJsonConverter.cs index 826f555cf..721dbce76 100644 --- a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonJsonObjectJsonConverter.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonJsonObjectJsonConverter.cs @@ -8,7 +8,7 @@ // 项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。 // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ - +#if NET6_0_OR_GREATER using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -18,7 +18,6 @@ namespace ThingsGateway.JsonSerialization; /// /// 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonJsonObjectJsonConverter : JsonConverter { /// @@ -50,7 +49,6 @@ public class NewtonsoftJsonJsonObjectJsonConverter : JsonConverter /// 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonJsonArrayJsonConverter : JsonConverter { /// @@ -77,4 +75,6 @@ public class NewtonsoftJsonJsonArrayJsonConverter : JsonConverter /// 解决 long 精度问题 /// -[SuppressSniffer] public class NewtonsoftJsonLongToStringJsonConverter : JsonConverter { /// @@ -79,7 +78,6 @@ public class NewtonsoftJsonLongToStringJsonConverter : JsonConverter /// /// 解决 long? 精度问题 /// -[SuppressSniffer] public class NewtonsoftJsonNullableLongToStringJsonConverter : JsonConverter { /// diff --git a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonTimeOnlyJsonConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonTimeOnlyJsonConverter.cs similarity index 99% rename from src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonTimeOnlyJsonConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonTimeOnlyJsonConverter.cs index 4d6007f96..61b19660f 100644 --- a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/NewtonsoftJson/NewtonsoftJsonTimeOnlyJsonConverter.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/NewtonsoftJson/NewtonsoftJsonTimeOnlyJsonConverter.cs @@ -8,7 +8,7 @@ // 项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。 // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ - +#if NET6_0_OR_GREATER using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -17,7 +17,6 @@ namespace ThingsGateway.JsonSerialization; /// /// TimeOnly 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonTimeOnlyJsonConverter : JsonConverter { /// @@ -72,7 +71,6 @@ public class NewtonsoftJsonTimeOnlyJsonConverter : JsonConverter /// /// TimeOnly? 类型序列化 /// -[SuppressSniffer] public class NewtonsoftJsonNullableTimeOnlyJsonConverter : JsonConverter { /// @@ -123,4 +121,6 @@ public class NewtonsoftJsonNullableTimeOnlyJsonConverter : JsonConverter -public class NewtonsoftEncodingConverter : Newtonsoft.Json.JsonConverter -{ - /// - public override Encoding? ReadJson(JsonReader reader, Type objectType, Encoding? existingValue, bool hasExistingValue, Newtonsoft.Json.JsonSerializer serializer) - { - // 从 JSON 字符串中读取编码名称,并创建相应的 Encoding 对象 - string? encodingName = reader.Value as string; - return Encoding.GetEncoding(encodingName ?? Encoding.UTF8.WebName); - } - - /// - public override void WriteJson(JsonWriter writer, Encoding? value, Newtonsoft.Json.JsonSerializer serializer) - { - writer.WriteValue(value.WebName); - } -} diff --git a/src/Admin/ThingsGateway.NewLife.X/Serialization/ExtendableConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/ExtendableConverter.cs similarity index 100% rename from src/Admin/ThingsGateway.NewLife.X/Serialization/ExtendableConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/ExtendableConverter.cs diff --git a/src/Admin/ThingsGateway.NewLife.X/Serialization/JsonConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/JsonConverter.cs similarity index 100% rename from src/Admin/ThingsGateway.NewLife.X/Serialization/JsonConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/JsonConverter.cs diff --git a/src/Admin/ThingsGateway.NewLife.X/Serialization/LocalTimeConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/LocalTimeConverter.cs similarity index 100% rename from src/Admin/ThingsGateway.NewLife.X/Serialization/LocalTimeConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/LocalTimeConverter.cs diff --git a/src/Admin/ThingsGateway.NewLife.X/Serialization/SafeInt64Converter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/SafeInt64Converter.cs similarity index 100% rename from src/Admin/ThingsGateway.NewLife.X/Serialization/SafeInt64Converter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/SafeInt64Converter.cs diff --git a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/SystemTextJson/SystemTextJsonDateOnlyJsonConverter.cs b/src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/SystemTextJsonDateOnlyJsonConverter.cs similarity index 98% rename from src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/SystemTextJson/SystemTextJsonDateOnlyJsonConverter.cs rename to src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/SystemTextJsonDateOnlyJsonConverter.cs index a267976c7..9bb5afea0 100644 --- a/src/Admin/ThingsGateway.Furion/JsonSerialization/Converters/SystemTextJson/SystemTextJsonDateOnlyJsonConverter.cs +++ b/src/Admin/ThingsGateway.NewLife.X/Extension/SystemTextJson/SystemTextJsonDateOnlyJsonConverter.cs @@ -8,6 +8,7 @@ // 项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。 // 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。 // ------------------------------------------------------------------------ +#if NET6_0_OR_GREATER using System.Text.Json; using System.Text.Json.Serialization; @@ -17,7 +18,6 @@ namespace ThingsGateway.JsonSerialization; /// /// DateOnly 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonDateOnlyJsonConverter : JsonConverter { /// @@ -69,7 +69,6 @@ public class SystemTextJsonDateOnlyJsonConverter : JsonConverter /// /// DateOnly? 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonNullableDateOnlyJsonConverter : JsonConverter { /// @@ -117,4 +116,6 @@ public class SystemTextJsonNullableDateOnlyJsonConverter : JsonConverter /// DateTime 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonDateTimeJsonConverter : JsonConverter { /// @@ -87,7 +87,6 @@ public class SystemTextJsonDateTimeJsonConverter : JsonConverter /// /// DateTime? 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonNullableDateTimeJsonConverter : JsonConverter { /// @@ -156,4 +155,6 @@ public class SystemTextJsonNullableDateTimeJsonConverter : JsonConverter /// DateTimeOffset 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonDateTimeOffsetJsonConverter : JsonConverter { /// @@ -87,7 +87,6 @@ public class SystemTextJsonDateTimeOffsetJsonConverter : JsonConverter /// DateTimeOffset? 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonNullableDateTimeOffsetJsonConverter : JsonConverter { /// @@ -156,4 +155,5 @@ public class SystemTextJsonNullableDateTimeOffsetJsonConverter : JsonConverter /// 解决 long 精度问题 /// -[SuppressSniffer] public class SystemTextJsonLongToStringJsonConverter : JsonConverter { /// @@ -75,7 +75,6 @@ public class SystemTextJsonLongToStringJsonConverter : JsonConverter /// /// 解决 long? 精度问题 /// -[SuppressSniffer] public class SystemTextJsonNullableLongToStringJsonConverter : JsonConverter { /// @@ -133,4 +132,5 @@ public class SystemTextJsonNullableLongToStringJsonConverter : JsonConverter /// TimeOnly 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonTimeOnlyJsonConverter : JsonConverter { /// @@ -69,7 +69,6 @@ public class SystemTextJsonTimeOnlyJsonConverter : JsonConverter /// /// TimeOnly? 类型序列化 /// -[SuppressSniffer] public class SystemTextJsonNullableTimeOnlyJsonConverter : JsonConverter { /// @@ -117,4 +116,5 @@ public class SystemTextJsonNullableTimeOnlyJsonConverter : JsonConverter /// /// - public static List SplitByLine(string text) + public static IEnumerable SplitByLine(string text) { - List lines = new List(); using (var sr = new StringReader(text)) { string line = sr.ReadLine(); while (line != null) { - lines.Add(line); - line = sr.ReadLine(); + yield return sr.ReadLine(); } } - return lines; } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/QuestDb/QuestDbRestAPI.cs b/src/Admin/ThingsGateway.SqlSugar/QuestDb/QuestDbRestAPI.cs index 4071f019b..d32e6b18f 100644 --- a/src/Admin/ThingsGateway.SqlSugar/QuestDb/QuestDbRestAPI.cs +++ b/src/Admin/ThingsGateway.SqlSugar/QuestDb/QuestDbRestAPI.cs @@ -22,7 +22,6 @@ namespace ThingsGateway.SqlSugar internal string url = string.Empty; internal string authorization = string.Empty; internal static Random random = new Random(); - // 可修改的数据库客户端 ISqlSugarClient db; /// @@ -126,7 +125,7 @@ namespace ThingsGateway.SqlSugar /// public Task BulkCopyAsync(string tableName, DataTable dataTable, string dateFormat = "yyyy/M/d H:mm:ss") { - Check.ExceptionEasy(string.IsNullOrEmpty(tableName), "need tablaeName ", "需要 tablaeNam 设置表名"); + if (string.IsNullOrEmpty(tableName)) { throw new SqlSugarLangException("need tablaeName ", "需要 tablaeNam 设置表名"); } var className = "QuestDbBulkMerge_" + false + tableName.GetNonNegativeHashCodeString(); var builder = this.db.DynamicBuilder().CreateClass(className, new SugarTable() { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoAccessory.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoAccessory.cs index b1d6e758a..e818a39ee 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoAccessory.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoAccessory.cs @@ -45,8 +45,8 @@ namespace ThingsGateway.SqlSugar else { // 如果不是匿名对象,抛异常 - Check.Exception(!entityType.IsAnonymousType(), - "参数格式错误。\n请使用 new{xx=xx, xx2=xx2} 或 \nDictionary 或 \nSugarParameter [] "); + if (!entityType.IsAnonymousType()) + throw new SqlSugarException("参数格式错误。{\n}请使用 new{xx=xx, xx2=xx2} 或 \nDictionary 或 \nSugarParameter [] "); // 反射对象属性转参数 return PropertyToParameter(parameters, propertyInfo, sqlParameterKeyWord, entityType).ToArray(); @@ -75,7 +75,7 @@ namespace ThingsGateway.SqlSugar value = DBNull.Value; // 特殊处理 HIERARCHYID 类型 - if (propertyty.Name.Contains("hierarchyid", StringComparison.CurrentCultureIgnoreCase)) + if (propertyty.Name.Contains("hierarchyid", StringComparison.OrdinalIgnoreCase)) { var parameter = new SugarParameter(sqlParameterKeyWord + propertyty.Name, SqlDbType.Udt) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoProvider.cs index 34bdc3ef4..6eaf199bd 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/AdoProvider/AdoProvider.cs @@ -267,9 +267,9 @@ namespace ThingsGateway.SqlSugar /// /// 异步打开连接 /// - public virtual async Task OpenAsync() + public virtual Task OpenAsync() { - await CheckConnectionAsync().ConfigureAwait(false); + return CheckConnectionAsync(); } /// @@ -356,9 +356,9 @@ namespace ThingsGateway.SqlSugar { if (this.Context.CurrentConnectionConfig?.DbType == DbType.SqlServer && ex.Message?.Contains("provider: SSL") == true) { - Check.ExceptionEasy(true, ex.Message, "SSL出错,因为升级了驱动,字符串增加Encrypt=True;TrustServerCertificate=True;即可。详细错误:" + ex.Message); + if (true) { throw new SqlSugarLangException(ex.Message, "SSL出错,因为升级了驱动,字符串增加Encrypt=True;TrustServerCertificate=True;即可。详细错误:" + ex.Message); } } - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message + $"DbType=\"{this.Context.CurrentConnectionConfig.DbType}\";ConfigId=\"{this.Context.CurrentConnectionConfig.ConfigId}\""); + { throw new SqlSugarException($"{ErrorMessage.ConnnectionOpen}{ex.Message}DbType=\"{this.Context.CurrentConnectionConfig.DbType}\";ConfigId=\"{this.Context.CurrentConnectionConfig.ConfigId}\""); } } } this.CheckConnectionAfter(this.Connection); @@ -383,7 +383,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message + $"DbType=\"{this.Context.CurrentConnectionConfig.DbType}\";ConfigId=\"{this.Context.CurrentConnectionConfig.ConfigId}\""); + { throw new SqlSugarException($"{ErrorMessage.ConnnectionOpen}{ex.Message}DbType=\"{this.Context.CurrentConnectionConfig.DbType}\";ConfigId=\"{this.Context.CurrentConnectionConfig.ConfigId}\""); } } } this.CheckConnectionAfter(this.Connection); @@ -1868,7 +1868,7 @@ namespace ThingsGateway.SqlSugar { if (sql?.Contains("{year}{month}{day}") == true) { - Check.ExceptionEasy("need .SplitTable() message:" + ex.Message, "当前代码是否缺少 .SplitTable() ,可以看文档 [分表] , 详细错误:" + ex.Message); + Check.ExceptionLang("need .SplitTable() message:" + ex.Message, "当前代码是否缺少 .SplitTable() ,可以看文档 [分表] , 详细错误:" + ex.Message); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs index 6d3938a5e..2d3bb0f7c 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs @@ -130,13 +130,13 @@ namespace ThingsGateway.SqlSugar var entityInfo = this.Context.GetEntityNoCacheInitMappingInfo(entityType); if (!this.Context.DbMaintenance.IsAnySystemTablePermissions()) { - Check.Exception(true, "Dbfirst and Codefirst requires system table permissions"); + { throw new SqlSugarException("Dbfirst and Codefirst requires system table permissions"); } } if (this.Context.Ado.Transaction == null) { var executeResult = Context.Ado.UseTran(() => Execute(entityType, entityInfo)); - Check.Exception(!executeResult.IsSuccess, executeResult.ErrorMessage); + if (!executeResult.IsSuccess) { throw new SqlSugarException(executeResult.ErrorMessage); } } else { @@ -294,7 +294,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.ExceptionEasy($"实体{type.Name} 出错,具体错误:" + ex.Message, $" {type.Name} error." + ex.Message); + Check.ExceptionLang($"实体{type.Name} 出错,具体错误:" + ex.Message, $" {type.Name} error." + ex.Message); } } return result; @@ -362,7 +362,7 @@ namespace ThingsGateway.SqlSugar //var entityInfo = this.Context.EntityMaintenance.GetEntityInfoNoCache(entityType); if (entityInfo.Discrimator.HasValue()) { - Check.ExceptionEasy(!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); + if (!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$")) { throw new SqlSugarLangException("The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); } var array = entityInfo.Discrimator.Split(','); foreach (var disItem in array) { @@ -490,7 +490,7 @@ namespace ThingsGateway.SqlSugar var dbColumn = entityInfo.Columns.FirstOrDefault(z => z.PropertyName == it.Key); if (dbColumn == null && entityInfo.Discrimator == null) { - Check.ExceptionEasy($"{entityInfo.EntityName} no SugarIndex[ {it.Key} ] found", $"类{entityInfo.EntityName} 索引特性没找到列 :{it.Key}"); + Check.ExceptionLang($"{entityInfo.EntityName} no SugarIndex[ {it.Key} ] found", $"类{entityInfo.EntityName} 索引特性没找到列 :{it.Key}"); } return new KeyValuePair(dbColumn.DbColumnName, it.Value); }) @@ -508,7 +508,7 @@ namespace ThingsGateway.SqlSugar public virtual void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { @@ -533,7 +533,7 @@ namespace ThingsGateway.SqlSugar { if (entityInfo.Columns.HasValue() && entityInfo.IsDisabledUpdateAll == false) { - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Multiple primary keys do not support modifications"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Multiple primary keys do not support modifications");} var tableName = GetTableName(entityInfo); var dbColumns = this.Context.DbMaintenance.GetColumnInfosByTableName(tableName, false); @@ -645,13 +645,13 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.GetThrowMessage("The current database does not support changing multiple primary keys. " + ex.Message, "当前数据库不支持修改多主键," + ex.Message)); + { throw new SqlSugarException(ErrorMessage.GetThrowMessage("The current database does not support changing multiple primary keys. " + ex.Message, "当前数据库不支持修改多主键," + ex.Message)); } throw; } } else if (!Enumerable.SequenceEqual(oldPkNames, newPkNames)) { - Check.Exception(true, ErrorMessage.GetThrowMessage("Modification of multiple primary key tables is not supported. Delete tables while creating", "不支持修改多主键表,请删除表在创建")); + { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Modification of multiple primary key tables is not supported. Delete tables while creating", "不支持修改多主键表,请删除表在创建")); } } } if (isChange && IsBackupTable) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/DbBindAccessory.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/DbBindAccessory.cs index 1756d58ac..685d9b300 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/DbBindAccessory.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/DbBindAccessory.cs @@ -56,7 +56,7 @@ namespace ThingsGateway.SqlSugar { if (ex.Message == "Common Language Runtime detected an invalid program.") { - Check.Exception(true, ErrorMessage.EntityMappingErrorCompositeFormat, ex.Message); + { throw new SqlSugarException($"{ErrorMessage.EntityMappingErrorCompositeFormat}{ex.Message}"); } } else { @@ -108,7 +108,7 @@ namespace ThingsGateway.SqlSugar { if (ex.Message == "Common Language Runtime detected an invalid program.") { - Check.Exception(true, ErrorMessage.EntityMappingErrorCompositeFormat, ex.Message); + { throw new SqlSugarException($"{ErrorMessage.EntityMappingErrorCompositeFormat}{ex.Message}"); } } else { @@ -409,7 +409,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, ErrorMessage.NotSupportedDictionaryCompositeFormat); + { throw new SqlSugarException(ErrorMessage.NotSupportedDictionaryCompositeFormat); } } } @@ -484,7 +484,7 @@ namespace ThingsGateway.SqlSugar else if (childType == UtilConstants.IntType) result.Add((T)Convert.ChangeType(array.Select(it => it.ObjToInt()).ToArray(), type)); else - Check.Exception(true, ErrorMessage.NotSupportedArrayCompositeFormat); + { throw new SqlSugarException(ErrorMessage.NotSupportedArrayCompositeFormat); } } /// diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/IDataRecordExtensions.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/IDataRecordExtensions.cs index 13e647f35..a2e17e48b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/IDataRecordExtensions.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbBindProvider/IDataRecordExtensions.cs @@ -466,7 +466,7 @@ namespace ThingsGateway.SqlSugar obj = dr.GetString(i); } var value = obj.ObjToString(); - return new SerializeService().DeserializeObject(value); + return DefaultServices.Serialize.DeserializeObject(value); } /// diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbFirstProvider/DbFirstProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbFirstProvider/DbFirstProvider.cs index 99fac4c6b..770542dbf 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbFirstProvider/DbFirstProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbFirstProvider/DbFirstProvider.cs @@ -112,7 +112,7 @@ namespace ThingsGateway.SqlSugar this.Context.Utilities.RemoveCacheAll(); if (!this.Context.DbMaintenance.IsAnySystemTablePermissions()) { - Check.Exception(true, "Dbfirst and Codefirst requires system table permissions"); + { throw new SqlSugarException("Dbfirst and Codefirst requires system table permissions"); } } this.TableInfoList = this.Context.Utilities.TranslateCopy(this.Context.DbMaintenance.GetTableInfoList()); var viewList = this.Context.Utilities.TranslateCopy(this.Context.DbMaintenance.GetViewInfoList()); @@ -239,7 +239,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, ErrorMessage.GetThrowMessage("Need to achieve ConnectionConfig.ConfigureExternal Services.RazorService", "需要实现 ConnectionConfig.ConfigureExternal Services.RazorService接口")); + { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Need to achieve ConnectionConfig.ConfigureExternal Services.RazorService", "需要实现 ConnectionConfig.ConfigureExternal Services.RazorService接口")); } } this.Context.Utilities.RemoveCacheAll(); result.FormatFileNameFunc = this.FormatFileNameFunc; @@ -371,7 +371,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, "Table '{0}' error,You can filter it with Db.DbFirst.Where(name=>name!=\"{0}\" ) \r\n Error message:{1}", tableInfo.Name, ex.Message); + { throw new SqlSugarException($"Table '{0}' error,You can filter it with Db.DbFirst.Where(name=>name!=\"{tableInfo.Name}\" ) {Environment.NewLine} Error message:{ex.Message}"); } } } } @@ -525,7 +525,7 @@ namespace ThingsGateway.SqlSugar public void CreateClassFile(string directoryPath, string nameSpace = "Models") { var seChar = Path.DirectorySeparatorChar.ToString(); - Check.ArgumentNullException(directoryPath, "directoryPath can't null"); + if (directoryPath == null) { throw new SqlSugarException("directoryPath can't null"); } var classStringList = ToClassStringList(nameSpace); if (classStringList.IsValuable()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbMaintenanceProvider/Methods.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbMaintenanceProvider/Methods.cs index 12e2c2fdf..2b7eb05e5 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbMaintenanceProvider/Methods.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DbMaintenanceProvider/Methods.cs @@ -206,7 +206,7 @@ namespace ThingsGateway.SqlSugar /// public virtual bool IsAnyTable(string tableName, bool isCache = true) { - Check.Exception(string.IsNullOrEmpty(tableName), "IsAnyTable tableName is not null"); + if (string.IsNullOrEmpty(tableName)) { throw new SqlSugarException("IsAnyTable tableName is not null"); } tableName = this.SqlBuilder.GetNoTranslationColumnName(tableName); var tables = GetTableInfoList(isCache); if (tables == null) return false; @@ -220,7 +220,7 @@ namespace ThingsGateway.SqlSugar columnName = this.SqlBuilder.GetNoTranslationColumnName(columnName); tableName = this.SqlBuilder.GetNoTranslationColumnName(tableName); var isAny = IsAnyTable(tableName, isCache); - Check.Exception(!isAny, string.Format("Table {0} does not exist", tableName)); + if (!isAny) { throw new SqlSugarException(string.Format("Table {0} does not exist", tableName)); } var columns = GetColumnInfosByTableName(tableName, isCache); if (columns.IsNullOrEmpty()) return false; return columns.Any(it => it.DbColumnName.Equals(columnName, StringComparison.CurrentCultureIgnoreCase)); @@ -232,7 +232,7 @@ namespace ThingsGateway.SqlSugar { columnName = this.SqlBuilder.GetNoTranslationColumnName(columnName); var isAny = IsAnyTable(tableName); - Check.Exception(!isAny, string.Format("Table {0} does not exist", tableName)); + if (!isAny) { throw new SqlSugarException(string.Format("Table {0} does not exist", tableName)); } var columns = GetColumnInfosByTableName(tableName); if (columns.IsNullOrEmpty()) return false; var result = columns.Any(it => it.IsPrimarykey && it.DbColumnName.Equals(columnName, StringComparison.CurrentCultureIgnoreCase)); @@ -245,7 +245,7 @@ namespace ThingsGateway.SqlSugar { columnName = this.SqlBuilder.GetNoTranslationColumnName(columnName); var isAny = IsAnyTable(tableName, isCache); - Check.Exception(!isAny, string.Format("Table {0} does not exist", tableName)); + if (!isAny) { throw new SqlSugarException(string.Format("Table {0} does not exist", tableName)); } var columns = GetColumnInfosByTableName(tableName, isCache); if (columns.IsNullOrEmpty()) return false; var result = columns.Any(it => it.IsPrimarykey && it.DbColumnName.Equals(columnName, StringComparison.CurrentCultureIgnoreCase)); @@ -258,7 +258,7 @@ namespace ThingsGateway.SqlSugar { columnName = this.SqlBuilder.GetNoTranslationColumnName(columnName); var isAny = IsAnyTable(tableName); - Check.Exception(!isAny, string.Format("Table {0} does not exist", tableName)); + if (!isAny) { throw new SqlSugarException(string.Format("Table {0} does not exist", tableName)); } var columns = GetColumnInfosByTableName(tableName); if (columns.IsNullOrEmpty()) return false; return columns.Any(it => it.IsIdentity && it.DbColumnName.Equals(columnName, StringComparison.CurrentCultureIgnoreCase)); @@ -360,7 +360,6 @@ namespace ThingsGateway.SqlSugar /// public virtual bool CreateDatabase(string databaseDirectory = null) { - var seChar = Path.DirectorySeparatorChar.ToString(); if (databaseDirectory.HasValue()) { databaseDirectory = databaseDirectory.TrimEnd('\\').TrimEnd('/'); @@ -1061,7 +1060,7 @@ namespace ThingsGateway.SqlSugar protected virtual string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } foreach (var item in columns) { string columnName = this.SqlBuilder.GetTranslationTableName(item.DbColumnName); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/DeleteableProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/DeleteableProvider.cs index 349da26e6..a8cff6362 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/DeleteableProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/DeleteableProvider.cs @@ -188,7 +188,7 @@ namespace ThingsGateway.SqlSugar var primaryFields = this.GetPrimaryKeys(); var isSinglePrimaryKey = primaryFields.Count == 1; var isNvarchar = false; - Check.Exception(primaryFields.IsNullOrEmpty(), string.Format("Table {0} with no primarykey", tableName)); + if (primaryFields.IsNullOrEmpty()) { throw new SqlSugarException(string.Format("Table {0} with no primarykey", tableName)); } if (isSinglePrimaryKey) { List primaryKeyValues = new List(); @@ -334,7 +334,7 @@ namespace ThingsGateway.SqlSugar { if (DeleteBuilder.WhereInfos.Count != 0 != true) { - Check.ExceptionEasy(!StaticConfig.EnableAllWhereIF, "Need to program startup configuration StaticConfig. EnableAllWhereIF = true; Tip: This operation is very risky if there are no conditions it is easy to update the entire table", " 需要程序启动时配置StaticConfig.EnableAllWhereIF=true; 提示:该操作存在很大的风险如果没有条件很容易将整个表全部更新"); + if (!StaticConfig.EnableAllWhereIF) { throw new SqlSugarLangException("Need to program startup configuration StaticConfig. EnableAllWhereIF = true; Tip: This operation is very risky if there are no conditions it is easy to update the entire table", " 需要程序启动时配置StaticConfig.EnableAllWhereIF=true; 提示:该操作存在很大的风险如果没有条件很容易将整个表全部更新"); } } if (isWhere) { @@ -383,7 +383,7 @@ namespace ThingsGateway.SqlSugar /// public IDeleteable WhereT(T deleteObj) { - Check.Exception(GetPrimaryKeys().IsNullOrEmpty(), "Where(entity) Primary key required"); + if (GetPrimaryKeys().IsNullOrEmpty()) { throw new SqlSugarException("Where(entity) Primary key required"); } Where([deleteObj]); return this; } @@ -606,7 +606,7 @@ namespace ThingsGateway.SqlSugar UtilMethods.StartCustomSplitTable(this.Context, typeof(T)); SplitTableDeleteByObjectProvider result = new SplitTableDeleteByObjectProvider(); result.Context = this.Context; - Check.ExceptionEasy(this.DeleteObjects == null, "SplitTable() +0 only List can be deleted", "SplitTable()无参数重载只支持根据实体集合删除"); + if (this.DeleteObjects == null) { throw new SqlSugarLangException("SplitTable() +0 only List can be deleted", "SplitTable()无参数重载只支持根据实体集合删除"); } result.deleteObjects = this.DeleteObjects; SplitTableContext helper = new SplitTableContext((SqlSugarProvider)Context) { @@ -653,7 +653,7 @@ namespace ThingsGateway.SqlSugar string tableName = this.Context.EntityMaintenance.GetTableName(); string primaryField = null; primaryField = GetPrimaryKeys().FirstOrDefault(); - Check.ArgumentNullException(primaryField, "Table " + tableName + " with no primarykey"); + if (primaryField == null) { throw new SqlSugarException("Table " + tableName + " with no primarykey"); } if (primaryKeyValues.Count < 10000) { Where(string.Format(DeleteBuilder.WhereInTemplate, SqlBuilder.GetTranslationColumnName(primaryField), primaryKeyValues.ToJoinSqlInVals())); @@ -741,7 +741,7 @@ namespace ThingsGateway.SqlSugar /// public DeleteablePage PageSize(int pageSize) { - Check.ExceptionEasy(this.DeleteObjects == null, "PageSize can only be deleted as a List entity collection", "Deleteable.PageSize()只能是List实体集合方式删除,并且集合不能为null"); + if (this.DeleteObjects == null) { throw new SqlSugarLangException("PageSize can only be deleted as a List entity collection", "Deleteable.PageSize()只能是List实体集合方式删除,并且集合不能为null"); } DeleteablePage result = new DeleteablePage(); result.DataList = this.DeleteObjects; result.Context = this.Context; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/LogicDeleteProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/LogicDeleteProvider.cs index 3f0b4138f..e4ead5491 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/LogicDeleteProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/LogicDeleteProvider.cs @@ -195,7 +195,7 @@ this.DeleteBuilder.WhereInfos.Add(whereItem); } - Check.ExceptionEasy(DeleteBuilder.GetWhereString == null, "Logical Delete requires a Where condition", "逻辑删除需要加Where条件"); + if (DeleteBuilder.GetWhereString == null) { throw new SqlSugarLangException("Logical Delete requires a Where condition", "逻辑删除需要加Where条件"); } where = DeleteBuilder.GetWhereString.Substring(5); pars = DeleteBuilder.Parameters; @@ -211,9 +211,10 @@ LogicFieldName = column.DbColumnName; } } - Check.Exception(LogicFieldName == null, ErrorMessage.GetThrowMessage( - $"{entityInfo.EntityName} is not isdelete or isdeleted" - , $"{entityInfo.EntityName} 没有IsDelete或者IsDeleted 的属性, 你也可以用 IsLogic().ExecuteCommand(\"列名\")")); + if (LogicFieldName == null) + throw new SqlSugarException(ErrorMessage.GetThrowMessage( + $"{entityInfo.EntityName} is not isdelete or isdeleted" + , $"{entityInfo.EntityName} 没有IsDelete或者IsDeleted 的属性, 你也可以用 IsLogic().ExecuteCommand(\"列名\")")); return LogicFieldName; } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/SplitTableDeleteByObjectProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/SplitTableDeleteByObjectProvider.cs index be58c0b6d..b9cc2912b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/SplitTableDeleteByObjectProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/DeleteProvider/SplitTableDeleteByObjectProvider.cs @@ -64,7 +64,7 @@ namespace ThingsGateway.SqlSugar private void GroupDataList(IEnumerable datas, out List groupModels, out int result) { var attribute = typeof(T).GetCustomAttribute() as SplitTableAttribute; - Check.Exception(attribute == null, $"{typeof(T).Name} need SplitTableAttribute"); + if (attribute == null) { throw new SqlSugarException($"{typeof(T).Name} need SplitTableAttribute"); } groupModels = new List(); var db = this.Context; var context = db.SplitHelper(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/EntityMaintenance/EntityMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/EntityMaintenance/EntityMaintenance.cs index 531fac02d..311fc1c93 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/EntityMaintenance/EntityMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/EntityMaintenance/EntityMaintenance.cs @@ -191,7 +191,7 @@ namespace ThingsGateway.SqlSugar public string GetDbColumnName(string propertyName, Type entityType) { var isAny = this.GetEntityInfo(entityType).Columns.Any(it => it.PropertyName.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase)); - Check.Exception(!isAny, "Property " + propertyName + " is Invalid"); + if (!isAny) { throw new SqlSugarException("Property " + propertyName + " is Invalid"); } var typeName = entityType.Name; if (this.Context.MappingColumns == null || this.Context.MappingColumns.Count == 0 || !this.Context.MappingColumns.Any(it => it.EntityName == typeName && it.PropertyName == propertyName)) { @@ -309,7 +309,7 @@ namespace ThingsGateway.SqlSugar } catch { - Check.ExceptionEasy("ORM error reading entity class XML, check entity XML or disable reading XML: MoreSettings IsNoReadXmlDescription set to true (same place to set DbType)", "ORM读取实体类的XML出现错误,检查实体XML或者禁用读取XML: MoreSettings里面的IsNoReadXmlDescription设为true (设置DbType的同一个地方)"); + Check.ExceptionLang("ORM error reading entity class XML, check entity XML or disable reading XML: MoreSettings IsNoReadXmlDescription set to true (same place to set DbType)", "ORM读取实体类的XML出现错误,检查实体XML或者禁用读取XML: MoreSettings里面的IsNoReadXmlDescription设为true (设置DbType的同一个地方)"); throw; } } @@ -523,14 +523,14 @@ namespace ThingsGateway.SqlSugar { column.IsIgnore = true; column.IsOwnsOne = true; - Check.ExceptionEasy(property.PropertyType.IsClass() == false, column.PropertyName + " IsOwnsOne必须用在类上面", column.PropertyName + "IsOwnsOne must be used on the class"); - Check.ExceptionEasy(property.PropertyType.FullName.IsCollectionsList() == true, column.PropertyName + " IsOwnsOne必须用在类上面", column.PropertyName + "IsOwnsOne must be used on the class"); + if (property.PropertyType.IsClass() == false) { throw new SqlSugarLangException(column.PropertyName + " IsOwnsOne必须用在类上面", column.PropertyName + "IsOwnsOne must be used on the class"); } + if (property.PropertyType.FullName.IsCollectionsList() == true) { throw new SqlSugarLangException(column.PropertyName + " IsOwnsOne必须用在类上面", column.PropertyName + "IsOwnsOne must be used on the class"); } var ownsOne = this.GetEntityInfoNoCache(property.PropertyType); foreach (var item in ownsOne.Columns) { if (result.Columns.Any(it => it.PropertyName.EqualCase(item.PropertyName) || it.DbColumnName.EqualCase(item.DbColumnName))) { - Check.ExceptionEasy($" {result.EntityName} " + item.PropertyName + " 存在重复定义 (IsOwnsOne) ", $" {result.EntityName} " + item.PropertyName + " Duplicate definition exists (IsOwnsOne)"); + Check.ExceptionLang($" {result.EntityName} " + item.PropertyName + " 存在重复定义 (IsOwnsOne) ", $" {result.EntityName} " + item.PropertyName + " Duplicate definition exists (IsOwnsOne)"); } item.ForOwnsOnePropertyInfo = column.PropertyInfo; result.Columns.Add(item); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavManyToMany.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavManyToMany.cs index dd4c0d9a1..3bdb4266a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavManyToMany.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavManyToMany.cs @@ -28,8 +28,8 @@ var thisPkColumn = thisEntity.Columns.FirstOrDefault(it => it.IsPrimarykey == true); // 检查主键是否存在 - Check.ExceptionEasy(thisPkColumn == null, $"{thisPkColumn.EntityName} need primary key", $"{thisPkColumn.EntityName}需要主键"); - Check.ExceptionEasy(parentPkColumn == null, $"{parentPkColumn.EntityName} need primary key", $"{parentPkColumn.EntityName}需要主键"); + if (thisPkColumn == null) { throw new SqlSugarLangException($"{thisPkColumn.EntityName} need primary key", $"{thisPkColumn.EntityName}需要主键"); } + if (parentPkColumn == null) { throw new SqlSugarLangException($"{parentPkColumn.EntityName} need primary key", $"{parentPkColumn.EntityName}需要主键"); } // 获取映射表信息 var mappingType = parentNavigateProperty.Navigat.MappingType; @@ -38,7 +38,7 @@ var mappingB = mappingEntity.Columns.FirstOrDefault(x => x.PropertyName == parentNavigateProperty.Navigat.MappingBId); // 检查映射配置是否正确 - Check.ExceptionEasy(mappingA == null || mappingB == null, $"Navigate property {name} error ", $"导航属性{name}配置错误"); + if (mappingA == null || mappingB == null) { throw new SqlSugarLangException($"Navigate property {name} error ", $"导航属性{name}配置错误"); } // 获取映射表主键列(排除关联字段) var mappingPk = mappingEntity.Columns diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavOneToOne.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavOneToOne.cs index 99c80da83..fbb92fee1 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavOneToOne.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavOneToOne.cs @@ -26,7 +26,7 @@ EntityColumnInfo thisPkColumn = GetPkColumnByNav(thisEntity, nav); // 检查主键列是否存在 - Check.Exception(thisPkColumn == null, $" Navigate {parentEntity.EntityName} : {name} is error ", $"导航实体 {parentEntity.EntityName} 属性 {name} 配置错误"); + if (thisPkColumn == null) { throw new SqlSugarException($" Navigate {parentEntity.EntityName} : {name} is error ", $"导航实体 {parentEntity.EntityName} 属性 {name} 配置错误"); } // 删除父表数据(如果尚未删除) if (!_IsDeletedParant) @@ -35,7 +35,7 @@ .ExecuteCommand()); // 检查导航列是否存在 - Check.ExceptionEasy(parentColumn == null, "The one-to-one navigation configuration is incorrect", "一对一导航配置错误"); + if (parentColumn == null) { throw new SqlSugarLangException("The one-to-one navigation configuration is incorrect", "一对一导航配置错误"); } // 获取父表导航列值列表 var ids = _ParentList.Select(it => parentColumn.PropertyInfo.GetValue(it)).ToList(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavProvider.cs index fd8f30365..0317fa0f6 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavProvider.cs @@ -78,7 +78,7 @@ namespace ThingsGateway.SqlSugar var nav = this._ParentEntity.Columns.FirstOrDefault(x => x.PropertyName == name); if (nav.Navigat == null) { - Check.ExceptionEasy($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); + Check.ExceptionLang($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); } if (nav.Navigat.NavigatType == NavigateType.OneToOne || nav.Navigat.NavigatType == NavigateType.ManyToOne) { @@ -111,7 +111,7 @@ namespace ThingsGateway.SqlSugar var nav = this._ParentEntity.Columns.FirstOrDefault(x => x.PropertyName == name); if (nav.Navigat == null) { - Check.ExceptionEasy($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); + Check.ExceptionLang($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); } if (nav.Navigat.NavigatType == NavigateType.OneToOne || nav.Navigat.NavigatType == NavigateType.ManyToOne) { @@ -143,7 +143,7 @@ namespace ThingsGateway.SqlSugar ActionMethodCallExpression(callMethod); newExp = callMethod.Arguments[0]; i++; - Check.Exception(i > 10000, expression + " is error"); + if (i > 10000) { throw new SqlSugarException($"{expression} is error"); } } return newExp; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavTask.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavTask.cs index 8e2deeb85..7a9f7e032 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavTask.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/DeleteNavTask.cs @@ -276,10 +276,9 @@ namespace ThingsGateway.SqlSugar /// 是否成功 public async Task ExecuteCommandAsync() { - await Task.Run(async () => + await Task.Run(() => { ExecuteCommand(); - await Task.Delay(0).ConfigureAwait(false); }).ConfigureAwait(false); return true; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProvider.cs index 774187cb4..a67c0b5bb 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProvider.cs @@ -147,7 +147,7 @@ namespace ThingsGateway.SqlSugar var nav = this._ParentEntity.Columns.FirstOrDefault(x => x.PropertyName == name); if (nav.Navigat == null) { - Check.ExceptionEasy($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); + Check.ExceptionLang($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); } if (nav.Navigat.NavigatType == NavigateType.OneToOne || nav.Navigat.NavigatType == NavigateType.ManyToOne) { @@ -189,7 +189,7 @@ namespace ThingsGateway.SqlSugar var nav = this._ParentEntity.Columns.FirstOrDefault(x => x.PropertyName == name); if (nav.Navigat == null) { - Check.ExceptionEasy($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); + Check.ExceptionLang($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); } if (nav.Navigat.NavigatType == NavigateType.OneToOne || nav.Navigat.NavigatType == NavigateType.ManyToOne) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderHelper.cs index 0e538940f..b491d9522 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderHelper.cs @@ -147,7 +147,7 @@ children = children.Distinct().ToList(); if (pkColumn == null) { - Check.ExceptionEasy($"{typeof(TChild).Name} need primary key ", $"{typeof(TChild).Name}需要主键"); + Check.ExceptionLang($"{typeof(TChild).Name} need primary key ", $"{typeof(TChild).Name}需要主键"); } var x = this._Context.Storageable(children).WhereColumns(new string[] { pkColumn.PropertyName }).GetStorageableResult(); var insertData = children = x.InsertList.Select(it => it.Item).ToList(); @@ -165,7 +165,7 @@ var updateData = x.UpdateList.Select(it => it.Item); children.AddRange(updateData); } - Check.ExceptionEasy(pkColumn == null && NavColumn == null, $"The entity is invalid", $"实体错误无法使用导航"); + if (pkColumn == null && NavColumn == null) { throw new SqlSugarLangException($"The entity is invalid", $"实体错误无法使用导航"); } InitData(pkColumn, insertData); this._ParentList = children.Cast().ToList(); } @@ -258,7 +258,7 @@ if (IsDefaultValue(pkColumn.PropertyInfo.GetValue(child))) { var name = pkColumn.EntityName + " " + pkColumn.DbColumnName; - Check.ExceptionEasy($"The field {name} is not an autoassignment type and requires an assignment", $"字段{name}不是可自动赋值类型需要赋值(并且不能是已存在值) , 可赋值类型有 自增、long、Guid、string"); + Check.ExceptionLang($"The field {name} is not an autoassignment type and requires an assignment", $"字段{name}不是可自动赋值类型需要赋值(并且不能是已存在值) , 可赋值类型有 自增、long、Guid、string"); } } if (IsFirst && _RootOptions != null) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderManyToMany.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderManyToMany.cs index 0cca8c610..d7878a168 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderManyToMany.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderManyToMany.cs @@ -24,15 +24,15 @@ namespace ThingsGateway.SqlSugar var thisPkColumn = thisEntity.Columns.FirstOrDefault(it => it.IsPrimarykey == true); // 检查主键是否存在 - Check.ExceptionEasy(thisPkColumn == null, $"{thisPkColumn.EntityName} need primary key", $"{thisPkColumn.EntityName}需要主键"); - Check.ExceptionEasy(parentPkColumn == null, $"{parentPkColumn.EntityName} need primary key", $"{parentPkColumn.EntityName}需要主键"); + if (thisPkColumn == null) { throw new SqlSugarLangException($"{thisPkColumn.EntityName} need primary key", $"{thisPkColumn.EntityName}需要主键"); } + if (parentPkColumn == null) { throw new SqlSugarLangException($"{parentPkColumn.EntityName} need primary key", $"{parentPkColumn.EntityName}需要主键"); } // 获取映射表信息 var mappingType = parentNavigateProperty.Navigat.MappingType; var mappingEntity = this._Context.EntityMaintenance.GetEntityInfo(mappingType); var mappingA = mappingEntity.Columns.FirstOrDefault(x => x.PropertyName == parentNavigateProperty.Navigat.MappingAId); var mappingB = mappingEntity.Columns.FirstOrDefault(x => x.PropertyName == parentNavigateProperty.Navigat.MappingBId); - Check.ExceptionEasy(mappingA == null || mappingB == null, $"Navigate property {name} error ", $"导航属性{name}配置错误"); + if (mappingA == null || mappingB == null) { throw new SqlSugarLangException($"Navigate property {name} error ", $"导航属性{name}配置错误"); } // 获取映射表主键列(排除关联字段) var mappingPk = mappingEntity.Columns @@ -213,7 +213,7 @@ namespace ThingsGateway.SqlSugar else { var name = mappingPk.EntityName + " " + mappingPk.DbColumnName; - Check.ExceptionEasy($"The field {name} is not an autoassignment type and requires an assignment", + Check.ExceptionLang($"The field {name} is not an autoassignment type and requires an assignment", $" 中间表主键字段{name}不是可自动赋值类型, 可赋值类型有 自增、long、Guid、string。你也可以删掉主键 用双主键"); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToMany.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToMany.cs index 242138cc1..768302738 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToMany.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToMany.cs @@ -71,7 +71,7 @@ namespace ThingsGateway.SqlSugar var isTreeChild = GetIsTreeChild(parentEntity, thisEntity); // 检查子实体是否有主键 - Check.ExceptionEasy(thisPkColumn == null, $"{thisEntity.EntityName}need primary key", $"实体{thisEntity.EntityName}需要主键"); + if (thisPkColumn == null) { throw new SqlSugarLangException($"{thisEntity.EntityName}need primary key", $"实体{thisEntity.EntityName}需要主键"); } // 根据条件决定是否插入数据 if (NotAny(name) || isTreeChild) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToOne.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToOne.cs index 45e29a780..db216057e 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToOne.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavProviderOneToOne.cs @@ -23,10 +23,10 @@ EntityColumnInfo thisPkColumn = GetPkColumnByNav(thisEntity, nav); // 检查主键列是否存在 - Check.ExceptionEasy(thisPkColumn == null, $" Navigate {parentEntity.EntityName} : {name} is error ", $"导航实体 {parentEntity.EntityName} 属性 {name} 配置错误"); + if (thisPkColumn == null) { throw new SqlSugarLangException($" Navigate {parentEntity.EntityName} : {name} is error ", $"导航实体 {parentEntity.EntityName} 属性 {name} 配置错误"); } // 检查是否配置了WhereSql(不支持插入) - Check.ExceptionEasy(nav.Navigat.WhereSql.HasValue(), $" {name} Navigate(NavType,WhereSql) no support insert ", $"导航一对一 {name} 配置了 Sql变量 不支持插入"); + if (nav.Navigat.WhereSql.HasValue()) { throw new SqlSugarLangException($" {name} Navigate(NavType,WhereSql) no support insert ", $"导航一对一 {name} 配置了 Sql变量 不支持插入"); } List childList = new List(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavTask.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavTask.cs index ce12ee6db..114902c45 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavTask.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/InsertNavTask.cs @@ -100,9 +100,11 @@ namespace ThingsGateway.SqlSugar /// 插入导航任务 public InsertNavTask Include(Expression> expression) where TChild : class, new() { - Check.ExceptionEasy(typeof(TChild).FullName.Contains("System.Collections.Generic.List`"), - " need where T: class, new() ", - "需要Class,new()约束,并且类属性中不能有required修饰符"); + if (typeof(TChild).FullName.Contains("System.Collections.Generic.List`")) + { + throw new SqlSugarLangException(" need where T: class, new() ", + "需要Class,new()约束,并且类属性中不能有required修饰符"); + } this.Context = insertNavProvider._Context; insertNavProvider.NavContext = this.NavContext; InsertNavTask result = new InsertNavTask(); @@ -140,9 +142,11 @@ namespace ThingsGateway.SqlSugar /// 插入导航任务 public InsertNavTask Include(Expression> expression, InsertNavOptions options) where TChild : class, new() { - Check.ExceptionEasy(typeof(TChild).FullName.Contains("System.Collections.Generic.List`"), - " need where T: class, new() ", - "需要Class,new()约束,并且类属性中不能有required修饰符"); + if (typeof(TChild).FullName.Contains("System.Collections.Generic.List`")) + { + throw new SqlSugarLangException(" need where T: class, new() ", + "需要Class,new()约束,并且类属性中不能有required修饰符"); + } this.Context = insertNavProvider._Context; insertNavProvider.NavContext = this.NavContext; InsertNavTask result = new InsertNavTask(); @@ -343,10 +347,9 @@ namespace ThingsGateway.SqlSugar public async Task ExecuteReturnEntityAsync() { Root result = null; - await Task.Run(async () => + await Task.Run(() => { result = ExecuteReturnEntity(); - await Task.Delay(0).ConfigureAwait(false); }).ConfigureAwait(false); return result; } @@ -375,10 +378,9 @@ namespace ThingsGateway.SqlSugar /// 是否成功 public async Task ExecuteCommandAsync() { - await Task.Run(async () => + await Task.Run(() => { ExecuteCommand(); - await Task.Delay(0).ConfigureAwait(false); }).ConfigureAwait(false); return true; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavManyToMany.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavManyToMany.cs index 78dd35344..5bca32a35 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavManyToMany.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavManyToMany.cs @@ -24,15 +24,15 @@ namespace ThingsGateway.SqlSugar var thisPkColumn = thisEntity.Columns.FirstOrDefault(it => it.IsPrimarykey == true); // 检查主键是否存在 - Check.ExceptionEasy(thisPkColumn == null, $"{thisPkColumn.EntityName} need primary key", $"{thisPkColumn.EntityName}需要主键"); - Check.ExceptionEasy(parentPkColumn == null, $"{parentPkColumn.EntityName} need primary key", $"{parentPkColumn.EntityName}需要主键"); + if (thisPkColumn == null) { throw new SqlSugarLangException($"{thisPkColumn.EntityName} need primary key", $"{thisPkColumn.EntityName}需要主键"); } + if (parentPkColumn == null) { throw new SqlSugarLangException($"{parentPkColumn.EntityName} need primary key", $"{parentPkColumn.EntityName}需要主键"); } // 获取映射表信息 var mappingType = parentNavigateProperty.Navigat.MappingType; var mappingEntity = this._Context.EntityMaintenance.GetEntityInfo(mappingType); var mappingA = mappingEntity.Columns.FirstOrDefault(x => x.PropertyName == parentNavigateProperty.Navigat.MappingAId); var mappingB = mappingEntity.Columns.FirstOrDefault(x => x.PropertyName == parentNavigateProperty.Navigat.MappingBId); - Check.ExceptionEasy(mappingA == null || mappingB == null, $"Navigate property {name} error ", $"导航属性{name}配置错误"); + if (mappingA == null || mappingB == null) { throw new SqlSugarLangException($"Navigate property {name} error ", $"导航属性{name}配置错误"); } // 获取映射表主键列(排除关联字段) var mappingPk = mappingEntity.Columns @@ -120,10 +120,11 @@ namespace ThingsGateway.SqlSugar { // 逻辑删除原有映射关系 var locgicColumn = thisEntity.Columns.FirstOrDefault(it => it.PropertyName.EqualCase("IsDeleted") || it.PropertyName.EqualCase("IsDelete")); - Check.ExceptionEasy( - locgicColumn == null, - thisEntity.EntityName + "Logical deletion requires the entity to have the IsDeleted property", - thisEntity.EntityName + "假删除需要实体有IsDeleted属性"); + if (locgicColumn == null) + { + throw new SqlSugarLangException(thisEntity.EntityName + "Logical deletion requires the entity to have the IsDeleted property", + thisEntity.EntityName + "假删除需要实体有IsDeleted属性"); + } List conditionalModels = new List(); conditionalModels.Add(new ConditionalModel() @@ -249,7 +250,7 @@ namespace ThingsGateway.SqlSugar else { var name = mappingPk.EntityName + " " + mappingPk.DbColumnName; - Check.ExceptionEasy($"The field {name} is not an autoassignment type and requires an assignment", + Check.ExceptionLang($"The field {name} is not an autoassignment type and requires an assignment", $" 中间表主键字段{name}不是可自动赋值类型, 可赋值类型有 自增、long、Guid、string。你也可以删掉主键 用双主键"); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToMany.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToMany.cs index d7c969d45..69b23ba3b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToMany.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToMany.cs @@ -81,10 +81,11 @@ namespace ThingsGateway.SqlSugar if (this._Options?.OneToManyEnableLogicDelete == true) { var locgicColumn = thisEntity.Columns.FirstOrDefault(it => it.PropertyName.EqualCase("IsDeleted") || it.PropertyName.EqualCase("IsDelete")); - Check.ExceptionEasy( - locgicColumn == null, - thisEntity.EntityName + "Logical deletion requires the entity to have the IsDeleted property", - thisEntity.EntityName + "假删除需要实体有IsDeleted属性"); + if (locgicColumn == null) + { + throw new SqlSugarLangException(thisEntity.EntityName + "Logical deletion requires the entity to have the IsDeleted property", + thisEntity.EntityName + "假删除需要实体有IsDeleted属性"); + } List conditionalModels = new List(); conditionalModels.Add(new ConditionalModel() { @@ -177,10 +178,11 @@ namespace ThingsGateway.SqlSugar if (this._Options?.OneToManyEnableLogicDelete == true) { var locgicColumn = thisEntity.Columns.FirstOrDefault(it => it.PropertyName.EqualCase("IsDeleted") || it.PropertyName.EqualCase("IsDelete")); - Check.ExceptionEasy( - locgicColumn == null, - thisEntity.EntityName + "Logical deletion requires the entity to have the IsDeleted property", - thisEntity.EntityName + "假删除需要实体有IsDeleted属性"); + if (locgicColumn == null) + { + throw new SqlSugarLangException(thisEntity.EntityName + "Logical deletion requires the entity to have the IsDeleted property", + thisEntity.EntityName + "假删除需要实体有IsDeleted属性"); + } List conditionalModels = new List(); conditionalModels.Add(new ConditionalModel() { @@ -325,7 +327,7 @@ namespace ThingsGateway.SqlSugar childIndex++; if (childIndex > 4) { - Check.ExceptionEasy("Removing too many levels", "安全机制限制删除脏数据层级不能超过7层"); + Check.ExceptionLang("Removing too many levels", "安全机制限制删除脏数据层级不能超过7层"); } foreach (var columnInfo in childs) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToOne.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToOne.cs index 8bddc6505..ad3d9b793 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToOne.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavOneToOne.cs @@ -23,8 +23,8 @@ var thisEntity = this._Context.EntityMaintenance.GetEntityInfo(); IsDeleted = thisEntity.Columns.Any(it => it.PropertyName.EqualCase("isdeleted") || it.PropertyName.EqualCase("isdelete")); EntityColumnInfo thisPkColumn = GetPkColumnByNav(thisEntity, nav); - Check.ExceptionEasy(thisPkColumn == null, $" Navigate {parentEntity.EntityName} : {name} is error ", $"导航实体 {parentEntity.EntityName} 属性 {name} 配置错误"); - Check.ExceptionEasy(nav.Navigat.WhereSql.HasValue(), $" {name} Navigate(NavType,WhereSql) no support update ", $"导航一对一 {name} 配置了 Sql变量 不支持更新"); + if (thisPkColumn == null) { throw new SqlSugarLangException($" Navigate {parentEntity.EntityName} : {name} is error ", $"导航实体 {parentEntity.EntityName} 属性 {name} 配置错误"); } + if (nav.Navigat.WhereSql.HasValue()) { throw new SqlSugarLangException($" {name} Navigate(NavType,WhereSql) no support update ", $"导航一对一 {name} 配置了 Sql变量 不支持更新"); } List childList = new List(); foreach (var parent in parentList) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProvider.cs index 3c79618a7..1a9c9ae4f 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProvider.cs @@ -138,7 +138,7 @@ namespace ThingsGateway.SqlSugar var nav = this._ParentEntity.Columns.FirstOrDefault(x => x.PropertyName == name); if (nav.Navigat == null) { - Check.ExceptionEasy($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); + Check.ExceptionLang($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); } if (_RootOptions?.IsDisableUpdateRoot == true) { @@ -184,7 +184,7 @@ namespace ThingsGateway.SqlSugar var nav = this._ParentEntity.Columns.FirstOrDefault(x => x.PropertyName == name); if (nav.Navigat == null) { - Check.ExceptionEasy($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); + Check.ExceptionLang($"{name} no navigate attribute", $"{this._ParentEntity.EntityName}的属性{name}没有导航属性"); } UpdateRoot(isRoot, nav); IsFirst = false; @@ -241,7 +241,7 @@ namespace ThingsGateway.SqlSugar { var updateable = this._Context.Updateable(_Roots); var exp = _Options.RootFunc as Expression>>; - Check.ExceptionEasy(exp == null, "UpdateOptions.RootFunc is error", "UpdateOptions.RootFunc"); + if (exp == null) { throw new SqlSugarLangException("UpdateOptions.RootFunc is error", "UpdateOptions.RootFunc"); } var com = exp.Compile(); com(updateable); updateable.ExecuteCommand(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProviderHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProviderHelper.cs index 6bbd497f1..ade1af08d 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProviderHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavProviderHelper.cs @@ -113,7 +113,7 @@ namespace ThingsGateway.SqlSugar private void InsertDatas(List children, EntityColumnInfo pkColumn, EntityColumnInfo NavColumn = null) where TChild : class, new() { children = children.Distinct().ToList(); - Check.ExceptionEasy(pkColumn == null, typeof(TChild).Name + " has no primary key", typeof(TChild).Name + "没有主键"); + if (pkColumn == null) { throw new SqlSugarLangException(typeof(TChild).Name + " has no primary key", typeof(TChild).Name + "没有主键"); } var whereName = pkColumn.PropertyName; if (_Options?.OneToOneSaveByPrimaryKey == true && pkColumn.IsPrimarykey == false) { @@ -126,12 +126,12 @@ namespace ThingsGateway.SqlSugar var x = this._Context.Storageable(children).WhereColumns(new string[] { whereName }).ToStorage(); var insertData = x.InsertList.Select(it => it.Item).ToList(); var updateData = x.UpdateList.Select(it => it.Item).ToList(); - Check.ExceptionEasy(pkColumn == null && NavColumn == null, $"The entity is invalid", $"实体错误无法使用导航"); + if (pkColumn == null && NavColumn == null) { throw new SqlSugarLangException($"The entity is invalid", $"实体错误无法使用导航"); } if (_Options?.CurrentFunc != null) { var updateable = x.AsUpdateable; var exp = _Options.CurrentFunc as Expression>>; - Check.ExceptionEasy(exp == null, "UpdateOptions.CurrentFunc is error", "UpdateOptions.CurrentFunc参数设置错误"); + if (exp == null) { throw new SqlSugarLangException("UpdateOptions.CurrentFunc is error", "UpdateOptions.CurrentFunc参数设置错误"); } var com = exp.Compile(); com(updateable); if (IsDeleted) @@ -254,7 +254,7 @@ namespace ThingsGateway.SqlSugar if (IsDefaultValue(pkColumn.PropertyInfo.GetValue(child))) { var name = pkColumn.EntityName + " " + pkColumn.DbColumnName; - Check.ExceptionEasy($"The field {name} is not an autoassignment type and requires an assignment", $"字段{name}不是可自动赋值类型,需要赋值 , 可赋值类型有 自增、long、Guid、string"); + Check.ExceptionLang($"The field {name} is not an autoassignment type and requires an assignment", $"字段{name}不是可自动赋值类型,需要赋值 , 可赋值类型有 自增、long、Guid、string"); } } this._Context.Insertable(UpdateData).ExecuteCommand(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavTask.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavTask.cs index 6642206b5..0e441ca24 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavTask.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/ExecuteNavProvider/UpdateNavTask.cs @@ -331,10 +331,9 @@ namespace ThingsGateway.SqlSugar /// 是否成功 public async Task ExecuteCommandAsync() { - await Task.Run(async () => + await Task.Run(() => { ExecuteCommand(); - await Task.Delay(0).ConfigureAwait(false); }).ConfigureAwait(false); return true; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastBuilder.cs index 48f605bc8..60b4a89bb 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastBuilder.cs @@ -62,8 +62,8 @@ namespace ThingsGateway.SqlSugar public virtual async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) { var sqlbuilder = this.Context.Queryable().SqlBuilder; - Check.ArgumentNullException(updateColumns.Length == 0, "update columns count is 0"); - Check.ArgumentNullException(whereColumns.Length == 0, "where columns count is 0"); + if (updateColumns.Length == 0) { throw new SqlSugarException("update columns count is 0"); } + if (whereColumns.Length == 0) { throw new SqlSugarException("where columns count is 0"); } var sets = string.Join(",", updateColumns.Select(it => $"TM.{sqlbuilder.GetTranslationColumnName(it)}=TE.{sqlbuilder.GetTranslationColumnName(it)}")); var wheres = string.Join(" AND ", whereColumns.Select(it => $"TM.{sqlbuilder.GetTranslationColumnName(it)}=TE.{sqlbuilder.GetTranslationColumnName(it)}")); string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastestProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastestProvider.cs index cc713e02b..46fe9b9aa 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastestProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/FastestProvider.cs @@ -29,13 +29,13 @@ namespace ThingsGateway.SqlSugar /// 批量插入DataTable数据 public int BulkCopy(DataTable dt) { - Check.ExceptionEasy(this.AsName.IsNullOrEmpty(), "need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); + if (this.AsName.IsNullOrEmpty()) { throw new SqlSugarLangException("need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); } return BulkCopyAsync(this.AsName, dt).ConfigureAwait(true).GetAwaiter().GetResult(); } /// 异步批量插入DataTable数据 public Task BulkCopyAsync(DataTable dt) { - Check.ExceptionEasy(this.AsName.IsNullOrEmpty(), "need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); + if (this.AsName.IsNullOrEmpty()) { throw new SqlSugarLangException("need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); } return BulkCopyAsync(this.AsName, dt); } /// 异步批量插入DataTable数据 @@ -137,7 +137,7 @@ namespace ThingsGateway.SqlSugar /// 批量更新DataTable数据 public int BulkUpdate(DataTable dataTable, string[] whereColumns, string[] updateColumns) { - Check.ExceptionEasy(this.AsName.IsNullOrEmpty(), "need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); + if (this.AsName.IsNullOrEmpty()) { throw new SqlSugarLangException("need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); } return BulkUpdateAsync(this.AsName, dataTable, whereColumns, updateColumns).ConfigureAwait(true).GetAwaiter().GetResult(); } /// 批量更新DataTable数据 @@ -145,7 +145,7 @@ namespace ThingsGateway.SqlSugar { string[] updateColumns = dataTable.Columns.Cast().Select(it => it.ColumnName).Where(it => !whereColumns.Contains(it)).ToArray(); whereColumns = dataTable.Columns.Cast().Select(it => it.ColumnName).Where(it => whereColumns.Contains(it)).ToArray(); - Check.ExceptionEasy(this.AsName.IsNullOrEmpty(), "need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); + if (this.AsName.IsNullOrEmpty()) { throw new SqlSugarLangException("need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); } return BulkUpdateAsync(this.AsName, dataTable, whereColumns, updateColumns).ConfigureAwait(true).GetAwaiter().GetResult(); } /// 异步批量更新DataTable数据 @@ -153,7 +153,7 @@ namespace ThingsGateway.SqlSugar { string[] updateColumns = dataTable.Columns.Cast().Select(it => it.ColumnName).Where(it => !whereColumns.Contains(it)).ToArray(); whereColumns = dataTable.Columns.Cast().Select(it => it.ColumnName).Where(it => whereColumns.Contains(it)).ToArray(); - Check.ExceptionEasy(this.AsName.IsNullOrEmpty(), "need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); + if (this.AsName.IsNullOrEmpty()) { throw new SqlSugarLangException("need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); } return BulkUpdateAsync(this.AsName, dataTable, whereColumns, updateColumns); } /// 异步批量更新DataTable数据 @@ -254,26 +254,49 @@ namespace ThingsGateway.SqlSugar try { Begin(datas, false, true); - Check.Exception(whereColumns == null || whereColumns.Length == 0, "where columns count=0 or need primary key"); - Check.Exception(whereColumns == null || whereColumns.Length == 0, "where columns count=0 or need primary key"); + if (whereColumns == null || whereColumns.Length == 0) { throw new SqlSugarException("where columns count=0 or need primary key"); } + if (whereColumns == null || whereColumns.Length == 0) { throw new SqlSugarException("where columns count=0 or need primary key"); } var isAuto = this.context.CurrentConnectionConfig.IsAutoCloseConnection; this.context.CurrentConnectionConfig.IsAutoCloseConnection = false; var old = this.context.Ado.IsDisableMasterSlaveSeparation; this.context.Ado.IsDisableMasterSlaveSeparation = true; - DataTable dt = ToDdateTable(datas); IFastBuilder buider = GetBuider(); buider.Context = context; - if (buider?.DbFastestProperties?.IsMerge == true) + int result = 0; + if (buider?.DbFastestProperties?.IsDataTable == true) { - await buider.CreateTempAsync(dt).ConfigureAwait(false); - await buider.ExecuteBulkCopyAsync(dt).ConfigureAwait(false); + var dt = ToDdateTable(datas); + if (buider?.DbFastestProperties?.IsMerge == true) + { + await buider.CreateTempAsync(dt).ConfigureAwait(false); + await buider.ExecuteBulkCopyAsync(dt).ConfigureAwait(false); + } + result = await buider.Merge(GetTableName(), dt, entityInfo, whereColumns, updateColumns, datas).ConfigureAwait(false); + //var queryTemp = this.context.Queryable().AS(dt.TableName).ToList();//test + //var result = await buider.UpdateByTempAsync(GetTableName(), dt.TableName, updateColumns, whereColumns); + if (buider?.DbFastestProperties?.IsMerge == true && this.context.CurrentConnectionConfig.DbType != DbType.Sqlite) + { + this.context.DbMaintenance.DropTable(dt.TableName); + } } - var result = await buider.Merge(GetTableName(), dt, entityInfo, whereColumns, updateColumns, datas).ConfigureAwait(false); - //var queryTemp = this.context.Queryable().AS(dt.TableName).ToList();//test - //var result = await buider.UpdateByTempAsync(GetTableName(), dt.TableName, updateColumns, whereColumns); - if (buider?.DbFastestProperties?.IsMerge == true && this.context.CurrentConnectionConfig.DbType != DbType.Sqlite) + else { - this.context.DbMaintenance.DropTable(dt.TableName); + var dict = ToDdict(datas); + string? tempName = string.Empty; + var tableName = GetTableName(); + if (buider?.DbFastestProperties?.IsMerge == true) + { + + tempName = await buider.CreateTempAsync(dict).ConfigureAwait(false); + await buider.ExecuteBulkCopyAsync(tableName, dict).ConfigureAwait(false); + } + result = await buider.Merge(tableName, dict, entityInfo, whereColumns, updateColumns, datas).ConfigureAwait(false); + //var queryTemp = this.context.Queryable().AS(dt.TableName).ToList();//test + //var result = await buider.UpdateByTempAsync(GetTableName(), dt.TableName, updateColumns, whereColumns); + if (buider?.DbFastestProperties?.IsMerge == true && this.context.CurrentConnectionConfig.DbType != DbType.Sqlite && !string.IsNullOrEmpty(tempName)) + { + this.context.DbMaintenance.DropTable(tempName); + } } this.context.CurrentConnectionConfig.IsAutoCloseConnection = isAuto; buider.CloseDb(); @@ -293,7 +316,7 @@ namespace ThingsGateway.SqlSugar /// 准备批量合并操作 private void _BulkMerge(DataTable dataTable, string[] whereColumns, out object newValue, out object fastestMethod, out MethodInfo bulkCopyMethod, bool isAsync, bool isIdentity) { - Check.ExceptionEasy(this.AsName.IsNullOrEmpty(), "need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); + if (this.AsName.IsNullOrEmpty()) { throw new SqlSugarLangException("need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); } var className = "BulkMerge_" + isIdentity + this.AsName.GetNonNegativeHashCodeString(); var builder = this.context.DynamicBuilder().CreateClass(className, new SugarTable() { @@ -327,7 +350,7 @@ namespace ThingsGateway.SqlSugar /// 准备批量合并操作 private void _BulkMerge(DataTable dataTable, string[] whereColumns, string[] updateColumns, out object newValue, out object fastestMethod, out MethodInfo bulkCopyMethod, bool isAsync, bool isIdentity) { - Check.ExceptionEasy(this.AsName.IsNullOrEmpty(), "need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); + if (this.AsName.IsNullOrEmpty()) { throw new SqlSugarLangException("need .AS(tablaeName) ", "需要 .AS(tablaeName) 设置表名"); } var className = "BulkMerge_" + isIdentity + this.AsName.GetNonNegativeHashCodeString(); var builder = this.context.DynamicBuilder().CreateClass(className, new SugarTable() { @@ -369,21 +392,44 @@ namespace ThingsGateway.SqlSugar try { Begin(datas, false); - Check.Exception(whereColumns == null || whereColumns.Length == 0, "where columns count=0 or need primary key"); - Check.Exception(updateColumns == null || updateColumns.Length == 0, "set columns count=0"); + if (whereColumns == null || whereColumns.Length == 0) { throw new SqlSugarException("where columns count=0 or need primary key"); } + if (updateColumns == null || updateColumns.Length == 0) { throw new SqlSugarException("set columns count=0"); } this.context.CurrentConnectionConfig.IsAutoCloseConnection = false; this.context.Ado.IsDisableMasterSlaveSeparation = true; - DataTable dt = ToDdateTable(datas); + + int result = 0; IFastBuilder buider = GetBuider(); - ActionIgnoreColumns(whereColumns, updateColumns, dt, buider.IsActionUpdateColumns); buider.Context = context; - await buider.CreateTempAsync(dt).ConfigureAwait(false); - await buider.ExecuteBulkCopyAsync(dt).ConfigureAwait(false); - //var queryTemp = this.context.Queryable().AS(dt.TableName).ToList();//test - var result = await buider.UpdateByTempAsync(GetTableName(), dt.TableName, updateColumns, whereColumns).ConfigureAwait(false); - if (this.context.CurrentConnectionConfig.DbType != DbType.Sqlite) + if (buider?.DbFastestProperties?.IsDataTable == true) { - this.context.DbMaintenance.DropTable(dt.TableName); + DataTable dt = ToDdateTable(datas); + + ActionIgnoreColumns(whereColumns, updateColumns, dt, buider.IsActionUpdateColumns); + + await buider.CreateTempAsync(dt).ConfigureAwait(false); + await buider.ExecuteBulkCopyAsync(dt).ConfigureAwait(false); + //var queryTemp = this.context.Queryable().AS(dt.TableName).ToList();//test + result = await buider.UpdateByTempAsync(GetTableName(), dt.TableName, updateColumns, whereColumns).ConfigureAwait(false); + if (this.context.CurrentConnectionConfig.DbType != DbType.Sqlite) + { + this.context.DbMaintenance.DropTable(dt.TableName); + } + } + else + { + var dict = ToDdict(datas); + ActionIgnoreColumns(whereColumns, updateColumns, dict, buider.IsActionUpdateColumns); + var tableName = GetTableName(); + + var tempName = await buider.CreateTempAsync(dict).ConfigureAwait(false); + await buider.ExecuteBulkCopyAsync(tableName, dict).ConfigureAwait(false); + //var queryTemp = this.context.Queryable().AS(dt.TableName).ToList();//test + result = await buider.UpdateByTempAsync(tableName, tempName, updateColumns, whereColumns).ConfigureAwait(false); + if (this.context.CurrentConnectionConfig.DbType != DbType.Sqlite) + { + this.context.DbMaintenance.DropTable(tempName); + } + } this.context.CurrentConnectionConfig.IsAutoCloseConnection = isAuto; isAutoOk = true; @@ -441,14 +487,59 @@ namespace ThingsGateway.SqlSugar } } } + /// 处理忽略列 + private void ActionIgnoreColumns(string[] whereColumns, string[] updateColumns, Dictionary)> list, bool IsActionUpdateColumns) + { + if (entityInfo.Columns.Where(it => it.IsIgnore == false).Count() > whereColumns.Length + updateColumns.Length && IsActionUpdateColumns) + { + var ignoreColumns = list + .Where(it => !whereColumns.Contains(it.Key) && !updateColumns.Contains(it.Key)); + foreach (var col in ignoreColumns) + { + if (col.Value.IsNullOrEmpty()) + { + if (col.Value.Item1 == UtilConstants.StringType) + { + foreach (var dataInfos in col.Value.Item2) + { + + dataInfos.Value = string.Empty; + if (this.queryable?.SqlBuilder?.SqlParameterKeyWord == ":") + { + dataInfos.Value = " "; + } + } + } + else if (col.Value.Item1 == UtilConstants.DateType) + { + foreach (var dataInfos in col.Value.Item2) + { + + dataInfos.Value = UtilMethods.GetMinDate(this.context.CurrentConnectionConfig); + + } + } + else + { + foreach (var dataInfos in col.Value.Item2) + { + + dataInfos.Value = Activator.CreateInstance(col.Value.Item1); + + } + } + } + } + } + } /// 执行批量更新操作 private async Task _BulkUpdate(string tableName, DataTable dataTable, string[] whereColumns, string[] updateColumns) { var datas = new string[dataTable.Rows.Count]; Begin(datas, false); - Check.Exception(whereColumns == null || whereColumns.Length == 0, "where columns count=0 or need primary key"); - Check.Exception(updateColumns == null || updateColumns.Length == 0, "set columns count=0"); + if (whereColumns == null || whereColumns.Length == 0) { throw new SqlSugarException("where columns count=0 or need primary key"); } + if (updateColumns == null || updateColumns.Length == 0) { throw new SqlSugarException("set columns count=0"); } var isAuto = this.context.CurrentConnectionConfig.IsAutoCloseConnection; this.context.CurrentConnectionConfig.IsAutoCloseConnection = false; var old = this.context.Ado.IsDisableMasterSlaveSeparation; @@ -484,10 +575,23 @@ namespace ThingsGateway.SqlSugar private async Task _BulkCopy(IReadOnlyCollection datas) { Begin(datas, true); - DataTable dt = ToDdateTable(datas); IFastBuilder buider = GetBuider(); buider.Context = context; - var result = await buider.ExecuteBulkCopyAsync(dt).ConfigureAwait(false); + int result = 0; + if (buider?.DbFastestProperties?.IsDataTable == true) + { + DataTable dt = ToDdateTable(datas); + result = await buider.ExecuteBulkCopyAsync(dt).ConfigureAwait(false); + + + } + else + { + var dict = ToDdict(datas); + var tableName = GetTableName(); + result = await buider.ExecuteBulkCopyAsync(tableName, dict).ConfigureAwait(false); + + } End(datas, true); return result; } @@ -566,4 +670,36 @@ namespace ThingsGateway.SqlSugar #endregion } -} \ No newline at end of file + + public class DataInfos + { + public DataInfos() + { + + } + public DataInfos(string name, object? value) + { + ColumnName = name; + Value = value; + } + + public string ColumnName { get; set; } + public object Value { get; set; } + } + + public static class DataInfosHelpers + { + public static IEnumerable GetRows(this Dictionary)> table, int rowIndex) + { + var enumerator = table.GetEnumerator(); + while (enumerator.MoveNext()) + { + var cur = enumerator.Current; + yield return cur.Value.Item2[rowIndex]; + } + + } + } +} + + diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/Private.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/Private.cs index a657dae31..ab3597310 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/Private.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/Private.cs @@ -155,6 +155,110 @@ namespace ThingsGateway.SqlSugar return dt; } + /// 将实体列表转换为DataTable + private Dictionary>> ToDdict(IEnumerable datas) + { + var builder = GetBuider(); + DataTable tempDataTable = ReflectionInoCore.GetInstance().GetOrCreate("BulkCopyAsync" + typeof(T).GetHashCode(), + () => + { + if (AsName == null) + { + return queryable.Where(it => false).Select("*").ToDataTable(); + } + else + { + return queryable.AS(AsName).Where(it => false).Select("*").ToDataTable(); + } + } + ); + HashSet uInt64TypeName = new HashSet(StringComparer.OrdinalIgnoreCase); + Dictionary>> results = new(StringComparer.OrdinalIgnoreCase); + foreach (DataColumn item in tempDataTable.Columns) + { + if (item.DataType == typeof(UInt64)) + { + uInt64TypeName.Add(item.ColumnName); + } + if (item.DataType.Name == "ClickHouseDecimal") + { + results.Add(item.ColumnName, (typeof(decimal), new())); + } + else + { + results.Add(item.ColumnName, (item.DataType, new())); + } + } + var columns = entityInfo.Columns; + if (columns.Where(it => !it.IsIgnore).Count() > tempDataTable.Columns.Count) + { + var tempColumns = tempDataTable.Columns.Cast().Select(it => it.ColumnName); + columns = columns.Where(it => tempColumns.Contains(it.DbColumnName)).ToList(); + } + var isMySql = this.context.CurrentConnectionConfig.DbType.IsIn(DbType.MySql, DbType.MySqlConnector); + var isSqliteCore = SugarCompatible.IsFramework == false && this.context.CurrentConnectionConfig.DbType.IsIn(DbType.Sqlite); + foreach (var item in datas) + { + foreach (var column in columns) + { + if (column.IsIgnore) + { + continue; + } + var name = column.DbColumnName; + if (name == null) + { + name = column.PropertyName; + } + var value = ValueConverter(column, GetValue(item, column)); + if (column.SqlParameterDbType != null && column.SqlParameterDbType is Type && UtilMethods.HasInterface((Type)column.SqlParameterDbType, typeof(ISugarDataConverter))) + { + var columnInfo = column; + var p = UtilMethods.GetParameterConverter(0, value, columnInfo); + value = p.Value; + } + else if (isMySql && column.UnderType == UtilConstants.BoolType) + { + if (value.ObjToBool() == false && uInt64TypeName.Any(z => z.EqualCase(column.DbColumnName))) + { + value = DBNull.Value; + } + } + else if (isSqliteCore && column.UnderType == UtilConstants.StringType && value is bool) + { + value = "isSqliteCore_" + value.ObjToString(); + } + else if (isSqliteCore && column.UnderType == UtilConstants.BoolType && value is bool) + { + value = Convert.ToBoolean(value) ? 1 : 0; + } + else if (column.UnderType == UtilConstants.DateTimeOffsetType && value != null && value != DBNull.Value) + { + if (builder.DbFastestProperties?.HasOffsetTime == true) + { + //Don't need to deal with + } + else + { + value = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)value); + } + } + else if (value != DBNull.Value && value != null && column.UnderType?.FullName == "System.TimeOnly") + { + value = UtilMethods.TimeOnlyToTimeSpan(value); + } + else if (value != DBNull.Value && value != null && column.UnderType?.FullName == "System.DateOnly") + { + value = UtilMethods.DateOnlyToDateTime(value); + } + var dr = new DataInfos(); + dr.ColumnName = column.DbColumnName; + dr.Value = value; + results[column.DbColumnName].Item2.Add(dr); + } + } + return results; + } /// 获取实体属性值 private static object GetValue(T item, EntityColumnInfo column) @@ -189,7 +293,7 @@ namespace ThingsGateway.SqlSugar return DBNull.Value; if (value is DateTime && (DateTime)value == DateTime.MinValue) { - value = Convert.ToDateTime("1900-01-01"); + return UtilMethods.MinDate; } else if (columnInfo.UnderType.IsEnum()) { @@ -316,7 +420,7 @@ namespace ThingsGateway.SqlSugar { if (!string.IsNullOrEmpty(CacheKey) || !string.IsNullOrEmpty(CacheKeyLike)) { - Check.Exception(this.context.CurrentConnectionConfig.ConfigureExternalServices?.DataInfoCacheService == null, "ConnectionConfig.ConfigureExternalServices.DataInfoCacheService is null"); + if (this.context.CurrentConnectionConfig.ConfigureExternalServices?.DataInfoCacheService == null) { throw new SqlSugarException("ConnectionConfig.ConfigureExternalServices.DataInfoCacheService is null"); } var service = this.context.CurrentConnectionConfig.ConfigureExternalServices?.DataInfoCacheService; if (!string.IsNullOrEmpty(CacheKey)) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/SplitFastest.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/SplitFastest.cs index d9f2d42d8..d05c3e18e 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/SplitFastest.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/FastestProvider/SplitFastest.cs @@ -119,7 +119,7 @@ namespace ThingsGateway.SqlSugar private IEnumerable GroupDataList(IEnumerable datas) { var attribute = typeof(T).GetCustomAttribute() as SplitTableAttribute; - Check.Exception(attribute == null, $"{typeof(T).Name} need SplitTableAttribute"); + if (attribute == null) { throw new SqlSugarException($"{typeof(T).Name} need SplitTableAttribute"); } var db = FastestProvider.context; var hasSplitField = typeof(T).GetProperties().Any(it => it.GetCustomAttribute() != null); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableHelper.cs index 59121b1cf..03f3143d1 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableHelper.cs @@ -192,18 +192,18 @@ namespace ThingsGateway.SqlSugar internal void Init() { InsertBuilder.EntityInfo = this.EntityInfo; - Check.Exception(InsertObjs == null || InsertObjs.Count == 0, "InsertObjs is null"); + if (InsertObjs == null || InsertObjs.Count == 0) { throw new SqlSugarException("InsertObjs is null"); } int i = 0; foreach (var item in InsertObjs) { List insertItem = new List(); if (item is Dictionary) { - Check.ExceptionEasy("To use Insertable dictionary, use string or object", "Insertable字典请使用string,object类型"); + Check.ExceptionLang("To use Insertable dictionary, use string or object", "Insertable字典请使用string,object类型"); } - if (item is Dictionary) + if (item is Dictionary dict) { - SetInsertItemByDic(i, item, insertItem); + SetInsertItemByDic(i, dict, insertItem); } else { @@ -284,9 +284,9 @@ namespace ThingsGateway.SqlSugar /// /// 通过字典设置插入项 /// - private void SetInsertItemByDic(int i, T item, List insertItem) + private void SetInsertItemByDic(int i, Dictionary item, List insertItem) { - foreach (var column in (item as Dictionary).OrderBy(it => it.Key)) + foreach (var column in item) { var columnInfo = new DbColumnInfo() { @@ -389,7 +389,7 @@ namespace ThingsGateway.SqlSugar } if (EntityInfo.Discrimator.HasValue()) { - Check.ExceptionEasy(!Regex.IsMatch(EntityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); + if (!Regex.IsMatch(EntityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$")) { throw new SqlSugarLangException("The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); } var array = EntityInfo.Discrimator.Split(','); foreach (var disItem in array) { @@ -459,7 +459,7 @@ namespace ThingsGateway.SqlSugar { if (StaticConfig.Check_StringIdentity) { - Check.ExceptionEasy(it.IsIdentity && it.UnderType == typeof(string), "Auto-incremented is not a string, how can I use a executable startup configuration: StaticConfig.Check_StringIdentity=false ", "自增不是能string,如何非要用可以程序启动配置:StaticConfig.Check_StringIdentity=false"); + if (it.IsIdentity && it.UnderType == typeof(string)) { throw new SqlSugarLangException("Auto-incremented is not a string, how can I use a executable startup configuration: StaticConfig.Check_StringIdentity=false ", "自增不是能string,如何非要用可以程序启动配置:StaticConfig.Check_StringIdentity=false"); } } return it.IsIdentity; }).Select(it => it.DbColumnName).ToList(); @@ -468,7 +468,7 @@ namespace ThingsGateway.SqlSugar //{ // if (this.Context.CurrentConnectionConfig.IsShardSameThread) // { - // Check.Exception(true, "IsShardSameThread=true can't be used async method"); + // {throw new SqlSugarException("IsShardSameThread=true can't be used async method");} // } // result.Start(); //} @@ -640,7 +640,7 @@ namespace ThingsGateway.SqlSugar } } } - Check.Exception(cons.IsNullOrEmpty(), "Insertable.EnableDiffLogEvent need primary key"); + if (cons.IsNullOrEmpty()) { throw new SqlSugarException("Insertable.EnableDiffLogEvent need primary key"); } var sqlable = this.SqlBuilder.ConditionalModelToSql(cons); whereSql = sqlable.Key; parameters.AddRange(sqlable.Value); @@ -693,7 +693,7 @@ namespace ThingsGateway.SqlSugar { var oldColumns = this.InsertBuilder.DbColumnInfoList.Select(it => it.PropertyName).ToHashSet(); var expression = (LambdaExpression.Lambda(method).Body as LambdaExpression).Body; - Check.Exception(!(expression is MethodCallExpression), method.ToString() + " is not method"); + if (!(expression is MethodCallExpression)) { throw new SqlSugarException($"{method} is not method"); } var callExpresion = expression as MethodCallExpression; UtilMethods.DataInoveByExpresson(this.InsertObjs, callExpresion); this.InsertBuilder.DbColumnInfoList = new List(); @@ -774,7 +774,7 @@ namespace ThingsGateway.SqlSugar } catch { - Check.ExceptionEasy($"long to ExecuteReturnPkList<{typeof(Type).Name}> error ", $" long 转换成ExecuteReturnPkList<{typeof(Type).Name}>失败"); + Check.ExceptionLang($"long to ExecuteReturnPkList<{typeof(Type).Name}> error ", $" long 转换成ExecuteReturnPkList<{typeof(Type).Name}>失败"); return null; } } @@ -784,7 +784,7 @@ namespace ThingsGateway.SqlSugar /// private List InsertPkListGuid(EntityColumnInfo pkInfo) { - Check.ExceptionEasy(pkInfo.UnderType.Name != typeof(Type).Name, $"{pkInfo.UnderType.Name} to ExecuteReturnPkList<{typeof(Type).Name}> error ", $" {pkInfo.UnderType.Name} 转换成ExecuteReturnPkList<{typeof(Type).Name}>失败"); + if (pkInfo.UnderType.Name != typeof(Type).Name) { throw new SqlSugarLangException($"{pkInfo.UnderType.Name} to ExecuteReturnPkList<{typeof(Type).Name}> error ", $" {pkInfo.UnderType.Name} 转换成ExecuteReturnPkList<{typeof(Type).Name}>失败"); } this.ExecuteCommand(); List result = new List(); if (InsertBuilder.DbColumnInfoList.HasValue()) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableProvider.cs index 4620cd74c..0177211fa 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/InsertableProvider.cs @@ -156,8 +156,8 @@ namespace ThingsGateway.SqlSugar public virtual List ExecuteReturnPkList() { var pkInfo = this.EntityInfo.Columns.FirstOrDefault(it => it.IsPrimarykey == true); - Check.ExceptionEasy(pkInfo == null, "ExecuteReturnPkList need primary key", "ExecuteReturnPkList需要主键"); - Check.ExceptionEasy(this.EntityInfo.Columns.Count(it => it.IsPrimarykey == true) > 1, "ExecuteReturnPkList ,Only support technology single primary key", "ExecuteReturnPkList只支技单主键"); + if (pkInfo == null) { throw new SqlSugarLangException("ExecuteReturnPkList need primary key", "ExecuteReturnPkList需要主键"); } + if (this.EntityInfo.Columns.Count(it => it.IsPrimarykey == true) > 1) { throw new SqlSugarLangException("ExecuteReturnPkList ,Only support technology single primary key", "ExecuteReturnPkList只支技单主键"); } var isIdEntity = pkInfo.IsIdentity || (pkInfo.OracleSequenceName.HasValue() && this.Context.CurrentConnectionConfig.DbType == DbType.Oracle); if (isIdEntity && this.InsertObjs.Count == 1) { @@ -267,8 +267,8 @@ namespace ThingsGateway.SqlSugar var id = SnowFlakeSingle.instance.getID(); var entity = this.Context.EntityMaintenance.GetEntityInfo(); var snowProperty = entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType); - Check.Exception(snowProperty == null, "The entity sets the primary key and is long"); - Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true"); + if (snowProperty == null) { throw new SqlSugarException("The entity sets the primary key and is long"); } + if (snowProperty.IsIdentity == true) { throw new SqlSugarException("SnowflakeId IsIdentity can't true"); } foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it => it.PropertyName == snowProperty.PropertyName)) { item.Value = id; @@ -286,8 +286,8 @@ namespace ThingsGateway.SqlSugar List result = new List(); var entity = this.Context.EntityMaintenance.GetEntityInfo(); var snowProperty = entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType); - Check.Exception(snowProperty == null, "The entity sets the primary key and is long"); - Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true"); + if (snowProperty == null) { throw new SqlSugarException("The entity sets the primary key and is long"); } + if (snowProperty.IsIdentity == true) { throw new SqlSugarException("SnowflakeId IsIdentity can't true"); } foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it => it.PropertyName == snowProperty.PropertyName)) { var id = SnowFlakeSingle.instance.getID(); @@ -321,8 +321,8 @@ namespace ThingsGateway.SqlSugar var id = SnowFlakeSingle.instance.getID(); var entity = this.Context.EntityMaintenance.GetEntityInfo(); var snowProperty = entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType); - Check.Exception(snowProperty == null, "The entity sets the primary key and is long"); - Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true"); + if (snowProperty == null) { throw new SqlSugarException("The entity sets the primary key and is long"); } + if (snowProperty.IsIdentity == true) { throw new SqlSugarException("SnowflakeId IsIdentity can't true"); } foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it => it.PropertyName == snowProperty.PropertyName)) { item.Value = id; @@ -340,8 +340,8 @@ namespace ThingsGateway.SqlSugar List result = new List(); var entity = this.Context.EntityMaintenance.GetEntityInfo(); var snowProperty = entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType); - Check.Exception(snowProperty == null, "The entity sets the primary key and is long"); - Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true"); + if (snowProperty == null) { throw new SqlSugarException("The entity sets the primary key and is long"); } + if (snowProperty.IsIdentity == true) { throw new SqlSugarException("SnowflakeId IsIdentity can't true"); } foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it => it.PropertyName == snowProperty.PropertyName)) { var id = SnowFlakeSingle.instance.getID(); @@ -415,7 +415,7 @@ namespace ThingsGateway.SqlSugar } } var idValue = ExecuteReturnBigIdentity(); - Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); + if (identityKeys.Count > 1) { throw new SqlSugarException("ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); } var identityKey = identityKeys[0]; object setValue = 0; if (idValue > int.MaxValue) @@ -585,7 +585,7 @@ namespace ThingsGateway.SqlSugar } } var idValue = await ExecuteReturnBigIdentityAsync().ConfigureAwait(false); - Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); + if (identityKeys.Count > 1) { throw new SqlSugarException("ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); } var identityKey = identityKeys[0]; object setValue = 0; if (idValue > int.MaxValue) @@ -746,7 +746,7 @@ namespace ThingsGateway.SqlSugar { if (isIgnoreNull) { - Check.Exception(this.InsertObjs.Count > 1, ErrorMessage.GetThrowMessage("ignoreNullColumn NoSupport batch insert, use .PageSize(1).IgnoreColumnsNull().ExecuteCommand()", "ignoreNullColumn 不支持批量操作,你可以用PageSzie(1).IgnoreColumnsNull().ExecuteCommand()")); + if (this.InsertObjs.Count > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("ignoreNullColumn NoSupport batch insert, use .PageSize(1).IgnoreColumnsNull().ExecuteCommand()", "ignoreNullColumn 不支持批量操作,你可以用PageSzie(1).IgnoreColumnsNull().ExecuteCommand()")); } this.InsertBuilder.IsNoInsertNull = true; } return this; @@ -863,7 +863,7 @@ namespace ThingsGateway.SqlSugar /// 可插入对象 public IInsertable IgnoreColumns(bool ignoreNullColumn, bool isOffIdentity = false) { - Check.Exception(this.InsertObjs.Count > 1 && ignoreNullColumn, ErrorMessage.GetThrowMessage("ignoreNullColumn NoSupport batch insert, use .PageSize(1).IgnoreColumnsNull().ExecuteCommand()", "ignoreNullColumn 不支持批量操作, 你可以使用 .PageSize(1).IgnoreColumnsNull().ExecuteCommand()")); + if (this.InsertObjs.Count > 1 && ignoreNullColumn) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("ignoreNullColumn NoSupport batch insert, use .PageSize(1).IgnoreColumnsNull().ExecuteCommand()", "ignoreNullColumn 不支持批量操作, 你可以使用 .PageSize(1).IgnoreColumnsNull().ExecuteCommand()")); } this.IsOffIdentity = isOffIdentity; this.InsertBuilder.IsOffIdentity = isOffIdentity; if (this.InsertBuilder.LambdaExpressions == null) @@ -915,7 +915,7 @@ namespace ThingsGateway.SqlSugar { PreToSql(); var currentType = this.Context.CurrentConnectionConfig.DbType; - Check.Exception(currentType != DbType.SqlServer, "UseSqlServer no support " + currentType); + if (currentType != DbType.SqlServer) { throw new SqlSugarException($"UseSqlServer no support {currentType}"); } SqlServerBlukCopy result = new SqlServerBlukCopy(); result.DbColumnInfoList = this.InsertBuilder.DbColumnInfoList.GroupBy(it => it.TableId).ToList(); result.InsertBuilder = this.InsertBuilder; @@ -936,7 +936,7 @@ namespace ThingsGateway.SqlSugar var currentType = this.Context.CurrentConnectionConfig.DbType; - Check.Exception(currentType != DbType.Oracle, "UseSqlServer no support " + currentType); + if (currentType != DbType.Oracle) { throw new SqlSugarException($"UseSqlServer no support {currentType}"); } OracleBlukCopy result = new OracleBlukCopy(); @@ -975,7 +975,7 @@ namespace ThingsGateway.SqlSugar /// 可插入对象 public IInsertable EnableDiffLogEvent(object businessData = null) { - //Check.Exception(this.InsertObjs.HasValue() && this.InsertObjs.Count() > 1, "DiffLog does not support batch operations"); + //if(this.InsertObjs.HasValue() && this.InsertObjs.Count() > 1){throw new SqlSugarException("DiffLog does not support batch operations");} DiffModel = new DiffLogModel(); this.IsEnableDiffLogEvent = true; DiffModel.BusinessData = businessData; @@ -990,10 +990,10 @@ namespace ThingsGateway.SqlSugar /// 可子插入对象 public ISubInsertable AddSubList(Expression> items) { - Check.Exception(GetPrimaryKeys().Count == 0, typeof(T).Name + " need Primary key"); - Check.Exception(GetPrimaryKeys().Count > 1, typeof(T).Name + "Multiple primary keys are not supported"); - //Check.Exception(this.InsertObjs.Count() > 1, "SubInserable No Support Insertable(List)"); - //Check.Exception(items.ToString().Contains(".First().")==false, items.ToString()+ " not supported "); + if (GetPrimaryKeys().Count == 0) { throw new SqlSugarException($"{typeof(T).Name} need Primary key"); } + if (GetPrimaryKeys().Count > 1) { throw new SqlSugarException($"{typeof(T).Name}Multiple primary keys are not supported"); } + //if(this.InsertObjs.Count() > 1){throw new SqlSugarException("SubInserable No Support Insertable(List)");} + //if(items.ToString().Contains(".First().")==false){throw new SqlSugarException(items.ToString()+ " not supported ");} if (this.InsertObjs == null || this.InsertObjs.Count == 0) { return new SubInsertable(); @@ -1015,10 +1015,11 @@ namespace ThingsGateway.SqlSugar /// 可子插入对象 public ISubInsertable AddSubList(Expression> tree) { - Check.Exception(GetPrimaryKeys().Count == 0, typeof(T).Name + " need Primary key"); - Check.Exception(GetPrimaryKeys().Count > 1, typeof(T).Name + "Multiple primary keys are not supported"); - //Check.Exception(this.InsertObjs.Count() > 1, "SubInserable No Support Insertable(List)"); - //Check.Exception(items.ToString().Contains(".First().")==false, items.ToString()+ " not supported "); + if (GetPrimaryKeys().Count == 0) + { throw new SqlSugarException($"{typeof(T).Name} need Primary key"); } + if (GetPrimaryKeys().Count > 1) { throw new SqlSugarException($"{typeof(T).Name}Multiple primary keys are not supported"); } + //if(this.InsertObjs.Count() > 1){throw new SqlSugarException("SubInserable No Support Insertable(List)");} + //if(items.ToString().Contains(".First().")==false){throw new SqlSugarException(items.ToString()+ " not supported ");} if (this.InsertObjs == null || this.InsertObjs.Count == 0) { return new SubInsertable(); @@ -1077,8 +1078,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, $" {typeof(T).Name} need SplitTableAttribute"); - return null; + { throw new SqlSugarException($" {typeof(T).Name} need SplitTableAttribute"); } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/SubInserable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/SubInserable.cs index b6c8ca4f6..9cff11b1a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/SubInserable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/InsertableProvider/SubInserable.cs @@ -65,7 +65,7 @@ namespace ThingsGateway.SqlSugar } catch { - Check.Exception(true, tree.ToString() + " format error "); + { throw new SqlSugarException($"{tree} format error "); } } return this; } @@ -346,7 +346,7 @@ namespace ThingsGateway.SqlSugar if (id.ObjToInt() == 0) { var primaryProperty = entityInfo.Columns.FirstOrDefault(it => it.IsPrimarykey); - Check.Exception(primaryProperty == null, entityInfo.EntityName + " no primarykey"); + if (primaryProperty == null) { throw new SqlSugarException($"{entityInfo.EntityName} no primarykey"); } pkValue = primaryProperty.PropertyInfo.GetValue(InsertObject); } else diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/Includes.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/Includes.cs index 8ece74875..ff86f4c01 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/Includes.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/Includes.cs @@ -158,7 +158,7 @@ namespace ThingsGateway.SqlSugar private static List GetIncludesByNameStringParameters(Type type, EntityColumnInfo item) { var parameters = new List(); - Check.ExceptionEasy(item == null, "\r\nThe \"IncludesByNameString\" method encountered an error. The navigation object does not exist. Please check the parameters and navigation configuration.", "IncludesByNameString方法出错,导航对象不存在,请检查参数和导航配置"); + if (item == null) { throw new SqlSugarLangException("\r\nThe \"IncludesByNameString\" method encountered an error. The navigation object does not exist. Please check the parameters and navigation configuration.", "IncludesByNameString方法出错,导航对象不存在,请检查参数和导航配置"); } var propertyType = item.PropertyInfo.PropertyType; var propertyItemType = propertyType; if (propertyType.FullName.IsCollectionsList()) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/MappingFieldsHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/MappingFieldsHelper.cs index 07176a9fe..af7a031c2 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/MappingFieldsHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/MappingFieldsHelper.cs @@ -155,7 +155,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.ExceptionEasy("MappingField max value is 5", "MappingField最大数量不能超过5"); + Check.ExceptionLang("MappingField max value is 5", "MappingField最大数量不能超过5"); } return setList; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/NavigatManager.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/NavigatManager.cs index 06540d6d0..9402019af 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/NavigatManager.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/NavigatManager.cs @@ -151,7 +151,7 @@ namespace ThingsGateway.SqlSugar var navObjectName = memberExpression.Member.Name; var navObjectNameProperty = listItemType.GetProperty(navObjectName); var navObjectNameColumnInfo = listItemEntity.Columns.First(it => it.PropertyName == navObjectName); - Check.ExceptionEasy(navObjectNameColumnInfo.Navigat == null, $"{navObjectName} not [Navigat(..)] ", $"{navObjectName} 没有导航特性 [Navigat(..)] "); + if (navObjectNameColumnInfo.Navigat == null) { throw new SqlSugarLangException($"{navObjectName} not [Navigat(..)] ", $"{navObjectName} 没有导航特性 [Navigat(..)] "); } if (navObjectNameColumnInfo.Navigat.NavigatType == NavigateType.OneToOne) { @@ -208,7 +208,7 @@ namespace ThingsGateway.SqlSugar { bPkColumn = bEntityInfo.Columns.FirstOrDefault(it => it.PropertyName == navObjectNameColumnInfo.Navigat.BClassId); } - Check.ExceptionEasy(bPkColumn == null, $"{bEntityInfo.EntityName} need primary key", $"{bEntityInfo.EntityName} 实体需要配置主键"); + if (bPkColumn == null) { throw new SqlSugarLangException($"{bEntityInfo.EntityName} need primary key", $"{bEntityInfo.EntityName} 实体需要配置主键"); } var bDb = this.Context; bDb = GetCrossDatabase(bDb, bEntity); bDb.InitMappingInfo(bEntity); @@ -217,7 +217,7 @@ namespace ThingsGateway.SqlSugar { listItemPkColumn = listItemEntity.Columns.FirstOrDefault(it => it.PropertyName == navObjectNameColumnInfo.Navigat.AClassId); } - Check.ExceptionEasy(listItemPkColumn == null, $"{listItemEntity.EntityName} need primary key", $"{listItemEntity.EntityName} 实体需要配置主键"); + if (listItemPkColumn == null) { throw new SqlSugarLangException($"{listItemEntity.EntityName} need primary key", $"{listItemEntity.EntityName} 实体需要配置主键"); } var ids = list.Select(it => it.GetType().GetProperty(listItemPkColumn.PropertyName).GetValue(it)).Select(it => it == null ? "null" : it).Distinct().ToList(); var mappingEntity = this.Context.EntityMaintenance.GetEntityInfo(navObjectNameColumnInfo.Navigat.MappingType); var aColumn = mappingEntity.Columns.First(it => it.PropertyName == navObjectNameColumnInfo.Navigat.MappingAId); @@ -336,7 +336,7 @@ namespace ThingsGateway.SqlSugar private void OneToOne(List list, Func, List> selector, EntityInfo listItemEntity, System.Reflection.PropertyInfo navObjectNameProperty, EntityColumnInfo navObjectNameColumnInfo) { var navColumn = listItemEntity.Columns.FirstOrDefault(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name); - Check.ExceptionEasy(navColumn == null, "OneToOne navigation configuration error", $"OneToOne导航配置错误: 实体{listItemEntity.EntityName} 不存在{navObjectNameColumnInfo.Navigat.Name}"); + if (navColumn == null) { throw new SqlSugarLangException("OneToOne navigation configuration error", $"OneToOne导航配置错误: 实体{listItemEntity.EntityName} 不存在{navObjectNameColumnInfo.Navigat.Name}"); } var navType = navObjectNameProperty.PropertyType; var db = this.Context; db = GetCrossDatabase(db, navType); @@ -344,14 +344,14 @@ namespace ThingsGateway.SqlSugar db.InitMappingInfo(navEntityInfo.Type); var navPkColumn = navEntityInfo.Columns.Where(it => it.IsPrimarykey).FirstOrDefault(); var navPkCount = navEntityInfo.Columns.Where(it => it.IsPrimarykey).Count(); - Check.ExceptionEasy(navPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null, navEntityInfo.EntityName + "need primarykey", navEntityInfo.EntityName + " 需要主键"); + if (navPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null) { throw new SqlSugarLangException(navEntityInfo.EntityName + "need primarykey", navEntityInfo.EntityName + " 需要主键"); } if (navObjectNameColumnInfo.Navigat.Name2.HasValue()) { navPkColumn = navEntityInfo.Columns.Where(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name2).FirstOrDefault(); } if (navPkColumn == null && navType.FullName.IsCollectionsList()) { - Check.ExceptionEasy($"{navObjectNameProperty.Name} type error ", $"一对一不能是List对象 {navObjectNameProperty.Name} "); + Check.ExceptionLang($"{navObjectNameProperty.Name} type error ", $"一对一不能是List对象 {navObjectNameProperty.Name} "); } List ids = null; var isOwnsOneProperty = IsOwnsOneProperty(listItemEntity, navObjectNameColumnInfo); @@ -510,7 +510,7 @@ namespace ThingsGateway.SqlSugar private void OneToMany(List list, Func, List> selector, EntityInfo listItemEntity, System.Reflection.PropertyInfo navObjectNameProperty, EntityColumnInfo navObjectNameColumnInfo) { - Check.ExceptionEasy(navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments().Length == 0, navObjectNameProperty?.Name + "Navigation configuration error one to many should be List", navObjectNameProperty?.Name + "导航配置错误一对多应该是List"); + if (navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments().Length == 0) { throw new SqlSugarLangException(navObjectNameProperty?.Name + "Navigation configuration error one to many should be List", navObjectNameProperty?.Name + "导航配置错误一对多应该是List"); } var navEntity = navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments()[0]; var navEntityInfo = this.Context.EntityMaintenance.GetEntityInfo(navEntity); @@ -518,14 +518,14 @@ namespace ThingsGateway.SqlSugar childDb = GetCrossDatabase(childDb, navEntityInfo.Type); childDb.InitMappingInfo(navEntityInfo.Type); var navColumn = navEntityInfo.Columns.FirstOrDefault(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name); - Check.ExceptionEasy(navColumn == null, $"{navEntityInfo.EntityName} not found {navObjectNameColumnInfo.Navigat.Name} ", $"实体 {navEntityInfo.EntityName} 未找到导航配置列 {navObjectNameColumnInfo.Navigat.Name} "); + if (navColumn == null) { throw new SqlSugarLangException($"{navEntityInfo.EntityName} not found {navObjectNameColumnInfo.Navigat.Name} ", $"实体 {navEntityInfo.EntityName} 未找到导航配置列 {navObjectNameColumnInfo.Navigat.Name} "); } //var navType = navObjectNameProperty.PropertyType; var listItemPkColumn = listItemEntity.Columns.Where(it => it.IsPrimarykey).FirstOrDefault(); - Check.ExceptionEasy(listItemPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null, listItemEntity.EntityName + " not primary key", listItemEntity.EntityName + "没有主键"); + if (listItemPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null) { throw new SqlSugarLangException(listItemEntity.EntityName + " not primary key", listItemEntity.EntityName + "没有主键"); } if (navObjectNameColumnInfo.Navigat.Name2.HasValue()) { listItemPkColumn = listItemEntity.Columns.Where(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name2).FirstOrDefault(); - Check.ExceptionEasy(listItemPkColumn == null, $"{navObjectNameColumnInfo.PropertyName} Navigate is error ", $"{navObjectNameColumnInfo.PropertyName}导航配置错误,可能顺序反了。"); + if (listItemPkColumn == null) { throw new SqlSugarLangException($"{navObjectNameColumnInfo.PropertyName} Navigate is error ", $"{navObjectNameColumnInfo.PropertyName}导航配置错误,可能顺序反了。"); } } var ids = list.Select(it => it.GetType().GetProperty(listItemPkColumn.PropertyName).GetValue(it)).Select(it => it == null ? "null" : it).Distinct().ToList(); List conditionalModels = new List(); @@ -648,7 +648,7 @@ namespace ThingsGateway.SqlSugar sqlObj.WhereString = navObjectNameColumnInfo?.Navigat?.Name2; } } - Check.ExceptionEasy(sqlObj.MappingExpressions.IsNullOrEmpty(), $"{expression} error,dynamic need MappingField ,Demo: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())", $"{expression} 解析出错,自定义映射需要 MappingField ,例子: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())"); + if (sqlObj.MappingExpressions.IsNullOrEmpty()) { throw new SqlSugarLangException($"{expression} error,dynamic need MappingField ,Demo: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())", $"{expression} 解析出错,自定义映射需要 MappingField ,例子: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())"); } if (list.Count != 0 && navObjectNameProperty.GetValue(list[0]) == null) { MappingFieldsHelper helper = new MappingFieldsHelper(); @@ -670,7 +670,7 @@ namespace ThingsGateway.SqlSugar private void OneToManyByArrayList(List list, Func, List> selector, EntityInfo listItemEntity, System.Reflection.PropertyInfo navObjectNamePropety, EntityColumnInfo navObjectNameColumnInfo) { - Check.ExceptionEasy(navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments().Length == 0, navObjectNamePropety?.Name + "Navigation configuration error one to many should be List", navObjectNamePropety?.Name + "导航配置错误一对多应该是List"); + if (navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments().Length == 0) { throw new SqlSugarLangException(navObjectNamePropety?.Name + "Navigation configuration error one to many should be List", navObjectNamePropety?.Name + "导航配置错误一对多应该是List"); } var navEntity = navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments()[0]; var navEntityInfo = this.Context.EntityMaintenance.GetEntityInfo(navEntity); @@ -678,15 +678,15 @@ namespace ThingsGateway.SqlSugar childDb = GetCrossDatabase(childDb, navEntityInfo.Type); childDb.InitMappingInfo(navEntityInfo.Type); var navColumn = listItemEntity.Columns.FirstOrDefault(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name); - Check.ExceptionEasy(navColumn == null, $"{navEntityInfo.EntityName} not found {navObjectNameColumnInfo.Navigat.Name} ", $"实体 {navEntityInfo.EntityName} 未找到导航配置列 {navObjectNameColumnInfo.Navigat.Name} "); - Check.ExceptionEasy(navColumn.IsJson == false && navColumn.IsArray == false, $"Entity {navEntityInfo.EntityName} navigation configuration errors {navObjectNameColumnInfo.Navigat.Name}, needs to array and IsJson = true or Pgsql IsArray = true ", $"实体 {navEntityInfo.EntityName} 导航配置错误 {navObjectNameColumnInfo.Navigat.Name} ,需要IsJson=true的数组或者pgsql如果是数组类型用 IsArray=true"); + if (navColumn == null) { throw new SqlSugarLangException($"{navEntityInfo.EntityName} not found {navObjectNameColumnInfo.Navigat.Name} ", $"实体 {navEntityInfo.EntityName} 未找到导航配置列 {navObjectNameColumnInfo.Navigat.Name} "); } + if (navColumn.IsJson == false && navColumn.IsArray == false) { throw new SqlSugarLangException($"Entity {navEntityInfo.EntityName} navigation configuration errors {navObjectNameColumnInfo.Navigat.Name}, needs to array and IsJson = true or Pgsql IsArray = true ", $"实体 {navEntityInfo.EntityName} 导航配置错误 {navObjectNameColumnInfo.Navigat.Name} ,需要IsJson=true的数组或者pgsql如果是数组类型用 IsArray=true"); } //var navType = navObjectNamePropety.PropertyType; var listItemPkColumn = navEntityInfo.Columns.Where(it => it.IsPrimarykey).FirstOrDefault(); - Check.ExceptionEasy(listItemPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null, listItemEntity.EntityName + " not primary key", listItemEntity.EntityName + "没有主键"); + if (listItemPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null) { throw new SqlSugarLangException(listItemEntity.EntityName + " not primary key", listItemEntity.EntityName + "没有主键"); } if (navObjectNameColumnInfo.Navigat.Name2.HasValue()) { listItemPkColumn = listItemEntity.Columns.Where(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name2).FirstOrDefault(); - Check.ExceptionEasy(listItemPkColumn == null, $"{navObjectNameColumnInfo.PropertyName} Navigate is error ", $"{navObjectNameColumnInfo.PropertyName}导航配置错误,可能顺序反了。"); + if (listItemPkColumn == null) { throw new SqlSugarLangException($"{navObjectNameColumnInfo.PropertyName} Navigate is error ", $"{navObjectNameColumnInfo.PropertyName}导航配置错误,可能顺序反了。"); } } var ids = list.Select(it => it.GetType().GetProperty(navColumn.PropertyName).GetValue(it)).SelectMany(it => (it as IEnumerable).Cast()).Distinct().ToList(); List conditionalModels = new List(); @@ -805,7 +805,7 @@ namespace ThingsGateway.SqlSugar sqlObj.WhereString = navObjectNameColumnInfo?.Navigat?.Name2; } } - Check.ExceptionEasy(sqlObj.MappingExpressions.IsNullOrEmpty(), $"{expression} error,dynamic need MappingField ,Demo: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())", $"{expression}解析出错, 自定义映射需要 MappingField ,例子: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())"); + if (sqlObj.MappingExpressions.IsNullOrEmpty()) { throw new SqlSugarLangException($"{expression} error,dynamic need MappingField ,Demo: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())", $"{expression}解析出错, 自定义映射需要 MappingField ,例子: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())"); } if (list.Count != 0 && navObjectNameProperty.GetValue(list[0]) == null) { MappingFieldsHelper helper = new MappingFieldsHelper(); @@ -941,24 +941,24 @@ namespace ThingsGateway.SqlSugar } else { - Check.ExceptionEasy($"no support {item}", $"不支持表达式{item} 不支持方法{method.Method.Name}"); + Check.ExceptionLang($"no support {item}", $"不支持表达式{item} 不支持方法{method.Method.Name}"); } if (queryable.QueryBuilder.Parameters != null) result.Parameters.AddRange(queryable.QueryBuilder.Parameters); } if (where.Count != 0) { - Check.ExceptionEasy(isList == false, $"{_ListCallFunc[0]} need is ToList()", $"{_ListCallFunc[0]} 需要ToList"); + if (isList == false) { throw new SqlSugarLangException($"{_ListCallFunc[0]} need is ToList()", $"{_ListCallFunc[0]} 需要ToList"); } result.WhereString = String.Join(" AND ", where); } if (orderBy.Count != 0) { - Check.ExceptionEasy(isList == false, $"{_ListCallFunc[0]} need is ToList()", $"{_ListCallFunc[0]} 需要ToList"); + if (isList == false) { throw new SqlSugarLangException($"{_ListCallFunc[0]} need is ToList()", $"{_ListCallFunc[0]} 需要ToList"); } result.OrderByString = String.Join(" , ", orderBy); } if (result.SelectString.HasValue()) { - Check.ExceptionEasy(isList == false, $"{_ListCallFunc[0]} need is ToList()", $"{_ListCallFunc[0]} 需要ToList"); + if (isList == false) { throw new SqlSugarLangException($"{_ListCallFunc[0]} need is ToList()", $"{_ListCallFunc[0]} 需要ToList"); } result.OrderByString = String.Join(" , ", orderBy); } return result; @@ -979,7 +979,7 @@ namespace ThingsGateway.SqlSugar var type = types[0]; var entityInfo = this.Context.EntityMaintenance.GetEntityInfo(type); this.Context.InitMappingInfo(type); - Check.ExceptionEasy(newExp.Type != entityInfo.Type, $" new {newExp.Type.Name}is error ,use Select(it=>new {entityInfo.Type.Name})", $"new {newExp.Type.Name}是错误的,请使用Select(it=>new {entityInfo.Type.Name})"); + if (newExp.Type != entityInfo.Type) { throw new SqlSugarLangException($" new {newExp.Type.Name}is error ,use Select(it=>new {entityInfo.Type.Name})", $"new {newExp.Type.Name}是错误的,请使用Select(it=>new {entityInfo.Type.Name})"); } if (!entityInfo.Columns.Any(x => x.Navigat != null)) { result.SelectString = (" " + queryable.QueryBuilder.GetExpressionValue(exp, ResolveExpressType.SelectSingle).GetString()); @@ -1101,11 +1101,11 @@ namespace ThingsGateway.SqlSugar var rootShortName = GetShortName(rootExpression); if (rootShortName.HasValue() && childExpression.ToString().Contains($" {rootShortName}.")) { - Check.ExceptionEasy($".Where({childExpression}) no support {rootShortName}.Field, Use .MappingField", $".Where({childExpression})禁止出{rootShortName}.字段 , 你可以使用.MappingField(z=>z.字段,()=>{rootShortName}.字段) 与主表字段进行过滤"); + Check.ExceptionLang($".Where({childExpression}) no support {rootShortName}.Field, Use .MappingField", $".Where({childExpression})禁止出{rootShortName}.字段 , 你可以使用.MappingField(z=>z.字段,()=>{rootShortName}.字段) 与主表字段进行过滤"); } else if (rootShortName.HasValue() && childExpression.ToString().Contains($"({rootShortName}.")) { - Check.ExceptionEasy($".Where({childExpression}) no support {rootShortName}.Field, Use .MappingField", $".Where({childExpression})禁止出{rootShortName}.字段 , 你可以使用.MappingField(z=>z.字段,()=>{rootShortName}.字段) 与主表字段进行过滤"); + Check.ExceptionLang($".Where({childExpression}) no support {rootShortName}.Field, Use .MappingField", $".Where({childExpression})禁止出{rootShortName}.字段 , 你可以使用.MappingField(z=>z.字段,()=>{rootShortName}.字段) 与主表字段进行过滤"); } } @@ -1182,11 +1182,11 @@ namespace ThingsGateway.SqlSugar { string m = item["m"] + ""; string c = item["c"] + ""; - Check.ExceptionEasy(m.IsNullOrEmpty() || c.IsNullOrEmpty(), $"{name} Navigation json format error, see documentation", $"{name}导航json格式错误,请看文档"); + if (m.IsNullOrEmpty() || c.IsNullOrEmpty()) { throw new SqlSugarLangException($"{name} Navigation json format error, see documentation", $"{name}导航json格式错误,请看文档"); } var cColumn = navEntityInfo.Columns.FirstOrDefault(it => it.PropertyName.EqualCase(c)); - Check.ExceptionEasy(cColumn == null, $"{c} does not exist in {navEntityInfo.EntityName}", $"{c}不存在于{navEntityInfo.EntityName}"); + if (cColumn == null) { throw new SqlSugarLangException($"{c} does not exist in {navEntityInfo.EntityName}", $"{c}不存在于{navEntityInfo.EntityName}"); } var mColumn = listItemEntity.Columns.FirstOrDefault(it => it.PropertyName.EqualCase(m)); - Check.ExceptionEasy(cColumn == null, $"{m} does not exist in {listItemEntity.EntityName}", $"{m}不存在于{listItemEntity.EntityName}"); + if (cColumn == null) { throw new SqlSugarLangException($"{m} does not exist in {listItemEntity.EntityName}", $"{m}不存在于{listItemEntity.EntityName}"); } sqlObj.MappingExpressions.Add(new MappingFieldsExpression() { LeftEntityColumn = cColumn, diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryMethodInfo.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryMethodInfo.cs index dea75a0f4..19ed64507 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryMethodInfo.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryMethodInfo.cs @@ -309,7 +309,7 @@ namespace ThingsGateway.SqlSugar { if (viewNameFomat?.Contains("{0}") != true) { - Check.ExceptionEasy("need{0}", "需要{0}表名的占位符"); + Check.ExceptionLang("need{0}", "需要{0}表名的占位符"); } var entityInfo = this.Context.EntityMaintenance.GetEntityInfo(EntityType); var viewName = string.Format(viewNameFomat, entityInfo.DbTableName); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSql.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSql.cs index ba05c7bf1..0ebc5eab4 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSql.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSql.cs @@ -28,8 +28,7 @@ namespace ThingsGateway.SqlSugar } else if (result.Count >= 2) { - Check.Exception(true, ErrorMessage.GetThrowMessage(".Single() result must not exceed one . You can use.First()", "使用single查询结果集不能大于1,适合主键查询,如果大于1你可以使用Queryable.First")); - return default(T); + { throw new SqlSugarException(ErrorMessage.GetThrowMessage(".Single() result must not exceed one . You can use.First()", "使用single查询结果集不能大于1,适合主键查询,如果大于1你可以使用Queryable.First")); } } else { @@ -298,7 +297,7 @@ namespace ThingsGateway.SqlSugar return _ToParentListByTreeKey(parentIdExpression, primaryKeyValue); } List result = new List(); - Check.Exception(entity.Columns.Any(it => it.IsPrimarykey), "No Primary key"); + if (entity.Columns.Any(it => it.IsPrimarykey)) { throw new SqlSugarException("No Primary key"); } var parentIdName = UtilConvert.ToMemberExpression((parentIdExpression as LambdaExpression).Body).Member.Name; var ParentInfo = entity.Columns.First(it => it.PropertyName == parentIdName); var parentPropertyName = ParentInfo.DbColumnName; @@ -322,7 +321,7 @@ namespace ThingsGateway.SqlSugar int i = 0; while (parentId != null && this.Context.Queryable().AS(tableName).WithCacheIF(this.IsCache, this.CacheTime).Filter(null, this.QueryBuilder.IsDisabledGobalFilter).ClearFilter(this.QueryBuilder.RemoveFilters).In([parentId]).Any()) { - Check.Exception(i > 200, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(200),检查最顶层的ParentId是否是null或者0")); + if (i > 200) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(200),检查最顶层的ParentId是否是null或者0")); } var parent = this.Context.Queryable().AS(tableName).WithCacheIF(this.IsCache, this.CacheTime).Filter(null, this.QueryBuilder.IsDisabledGobalFilter).InSingle(parentId); result.Add(parent); parentId = ParentInfo.PropertyInfo.GetValue(parent, null); @@ -340,7 +339,7 @@ namespace ThingsGateway.SqlSugar return _ToParentListByTreeKey(parentIdExpression, primaryKeyValue, parentWhereExpression); } List result = new List(); - Check.Exception(entity.Columns.Any(it => it.IsPrimarykey), "No Primary key"); + if (entity.Columns.Any(it => it.IsPrimarykey)) { throw new SqlSugarException("No Primary key"); } var parentIdName = UtilConvert.ToMemberExpression((parentIdExpression as LambdaExpression).Body).Member.Name; var ParentInfo = entity.Columns.First(it => it.PropertyName == parentIdName); var parentPropertyName = ParentInfo.DbColumnName; @@ -364,7 +363,7 @@ namespace ThingsGateway.SqlSugar int i = 0; while (parentId != null && this.Context.Queryable().AS(tableName).WhereIF(parentWhereExpression != default, parentWhereExpression).Filter(null, this.QueryBuilder.IsDisabledGobalFilter).In([parentId]).Any()) { - Check.Exception(i > 200, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(200),检查最顶层的ParentId是否是null或者0")); + if (i > 200) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(200),检查最顶层的ParentId是否是null或者0")); } var parent = this.Context.Queryable().AS(tableName).WhereIF(parentWhereExpression != default, parentWhereExpression).Filter(null, this.QueryBuilder.IsDisabledGobalFilter).InSingle(parentId); result.Add(parent); parentId = ParentInfo.PropertyInfo.GetValue(parent, null); @@ -814,7 +813,7 @@ namespace ThingsGateway.SqlSugar } public virtual void ForEach(Action action, int singleMaxReads = 300, System.Threading.CancellationTokenSource cancellationTokenSource = null) { - Check.Exception(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0, ErrorMessage.GetThrowMessage("no support Skip take, use PageForEach", "不支持Skip Take,请使用 Queryale.PageForEach")); + if (this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("no support Skip take, use PageForEach", "不支持Skip Take,请使用 Queryale.PageForEach")); } var totalNumber = 0; var totalPage = 1; for (int i = 1; i <= totalPage; i++) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSqlAsync.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSqlAsync.cs index fcb432089..ddb10b92f 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSqlAsync.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableExecuteSqlAsync.cs @@ -20,7 +20,7 @@ namespace ThingsGateway.SqlSugar { return default(T); } - Check.Exception(this.QueryBuilder.SelectValue.HasValue(), "'InSingle' and' Select' can't be used together,You can use .Select(it=>...).Single(it.id==1)"); + if (this.QueryBuilder.SelectValue.HasValue()) { throw new SqlSugarException("'InSingle' and' Select' can't be used together,You can use .Select(it=>...).Single(it.id==1)"); } var list = await In([pkValue]).ToListAsync().ConfigureAwait(false); if (list == null) return default(T); else return list.SingleOrDefault(); @@ -47,8 +47,7 @@ namespace ThingsGateway.SqlSugar } else if (result.Count == 2) { - Check.Exception(true, ErrorMessage.GetThrowMessage(".Single() result must not exceed one . You can use.First()", "使用single查询结果集不能大于1,适合主键查询,如果大于1你可以使用Queryable.First")); - return default(T); + { throw new SqlSugarException(ErrorMessage.GetThrowMessage(".Single() result must not exceed one . You can use.First()", "使用single查询结果集不能大于1,适合主键查询,如果大于1你可以使用Queryable.First")); } } else { @@ -457,7 +456,7 @@ namespace ThingsGateway.SqlSugar public virtual async Task ForEachAsync(Action action, int singleMaxReads = 300, System.Threading.CancellationTokenSource cancellationTokenSource = null) { - Check.Exception(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0, ErrorMessage.GetThrowMessage("no support Skip take, use PageForEach", "不支持Skip Take,请使用 Queryale.PageForEach")); + if (this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("no support Skip take, use PageForEach", "不支持Skip Take,请使用 Queryale.PageForEach")); } RefAsync totalNumber = 0; RefAsync totalPage = 1; for (int i = 1; i <= totalPage; i++) @@ -672,7 +671,7 @@ ParameterT parameter) { return await _ToParentListByTreeKeyAsync(parentIdExpression, primaryKeyValue).ConfigureAwait(false); } - Check.Exception(entity.Columns.Any(it => it.IsPrimarykey), "No Primary key"); + if (entity.Columns.Any(it => it.IsPrimarykey)) { throw new SqlSugarException("No Primary key"); } var parentIdName = UtilConvert.ToMemberExpression((parentIdExpression as LambdaExpression).Body).Member.Name; var ParentInfo = entity.Columns.First(it => it.PropertyName == parentIdName); var parentPropertyName = ParentInfo.DbColumnName; @@ -696,7 +695,7 @@ ParameterT parameter) int i = 0; while (parentId != null && await Context.Queryable().AS(tableName).Filter(null, QueryBuilder.IsDisabledGobalFilter).In([parentId]).AnyAsync().ConfigureAwait(false)) { - Check.Exception(i > 100, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); + if (i > 100) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); } var parent = await Context.Queryable().AS(tableName).WithCacheIF(IsCache, CacheTime).Filter(null, QueryBuilder.IsDisabledGobalFilter).InSingleAsync(parentId).ConfigureAwait(false); result.Add(parent); parentId = ParentInfo.PropertyInfo.GetValue(parent, null); @@ -714,7 +713,7 @@ ParameterT parameter) { return await _ToParentListByTreeKeyAsync(parentIdExpression, primaryKeyValue, parentWhereExpression).ConfigureAwait(false); } - Check.Exception(entity.Columns.Any(it => it.IsPrimarykey), "No Primary key"); + if (entity.Columns.Any(it => it.IsPrimarykey)) { throw new SqlSugarException("No Primary key"); } var parentIdName = UtilConvert.ToMemberExpression((parentIdExpression as LambdaExpression).Body).Member.Name; var ParentInfo = entity.Columns.First(it => it.PropertyName == parentIdName); var parentPropertyName = ParentInfo.DbColumnName; @@ -738,7 +737,7 @@ ParameterT parameter) int i = 0; while (parentId != null && await Context.Queryable().AS(tableName).WhereIF(parentWhereExpression != default, parentWhereExpression).Filter(null, QueryBuilder.IsDisabledGobalFilter).In([parentId]).AnyAsync().ConfigureAwait(false)) { - Check.Exception(i > 100, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); + if (i > 100) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); } var parent = await Context.Queryable().AS(tableName).WhereIF(parentWhereExpression != default, parentWhereExpression).Filter(null, QueryBuilder.IsDisabledGobalFilter).InSingleAsync(parentId).ConfigureAwait(false); result.Add(parent); parentId = ParentInfo.PropertyInfo.GetValue(parent, null); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableHelper.cs index 9384cab06..d44a1cc91 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableHelper.cs @@ -54,7 +54,7 @@ namespace ThingsGateway.SqlSugar FieldName = treeKey.DbColumnName } }).Any()) { - Check.Exception(i > 100, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); + if (i > 100) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); } var parent = this.Context.Queryable().AS(tableName).Filter(null, this.QueryBuilder.IsDisabledGobalFilter).Where(new List() { new ConditionalModel() { @@ -112,7 +112,7 @@ namespace ThingsGateway.SqlSugar FieldName = treeKey.DbColumnName } }).Any()) { - Check.Exception(i > 100, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); + if (i > 100) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); } var parent = this.Context.Queryable().AS(tableName).WhereIF(parentWhereExpression != default, parentWhereExpression).Filter(null, this.QueryBuilder.IsDisabledGobalFilter).Where(new List() { new ConditionalModel() { @@ -171,7 +171,7 @@ namespace ThingsGateway.SqlSugar FieldName = treeKey.DbColumnName } }).AnyAsync().ConfigureAwait(false)) { - Check.Exception(i > 100, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); + if (i > 100) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); } var parent = await Context.Queryable().AS(tableName).Filter(null, QueryBuilder.IsDisabledGobalFilter).Where(new List() { new ConditionalModel() { @@ -230,7 +230,7 @@ namespace ThingsGateway.SqlSugar FieldName = treeKey.DbColumnName } }).AnyAsync().ConfigureAwait(false)) { - Check.Exception(i > 100, ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); + if (i > 100) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Dead cycle", "出现死循环或超出循环上限(100),检查最顶层的ParentId是否是null或者0")); } var parent = await Context.Queryable().AS(tableName).WhereIF(parentWhereExpression != default, parentWhereExpression).Filter(null, QueryBuilder.IsDisabledGobalFilter).Where(new List() { new ConditionalModel() { @@ -377,7 +377,7 @@ namespace ThingsGateway.SqlSugar } private static string GetTreeKey(EntityInfo entity) { - Check.Exception(entity.Columns.Any(it => it.IsPrimarykey || it.IsTreeKey), "need IsPrimary=true Or IsTreeKey=true"); + if (entity.Columns.Any(it => it.IsPrimarykey || it.IsTreeKey)) { throw new SqlSugarException("need IsPrimary=true Or IsTreeKey=true"); } string pk = entity.Columns.Where(it => it.IsTreeKey).FirstOrDefault()?.PropertyName; if (pk == null) pk = entity.Columns.Where(it => it.IsPrimarykey).FirstOrDefault()?.PropertyName; @@ -794,7 +794,7 @@ namespace ThingsGateway.SqlSugar catch (Exception ex) { var errorExp = item.Value.ExpressionList.Last().ToString(); - Check.ExceptionEasy($"{errorExp} no support,{ex.Message}", $"{errorExp}语法不支持,请查SqlSugar文档询导航DTO用法,{ex.Message}"); + Check.ExceptionLang($"{errorExp} no support,{ex.Message}", $"{errorExp}语法不支持,请查SqlSugar文档询导航DTO用法,{ex.Message}"); } // // 重新构造Lambda表达式,将参数替换为新的参数,方法调用替换为新的方法调用 // var newExpression = Expression.Lambda>>(newMethodCallExpr, paramExpr); @@ -892,7 +892,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, "{0} and {1} are not a type, Try .select().mapper().ToList", typeof(TResult).FullName, typeof(T).FullName); + { throw new SqlSugarException($"{typeof(TResult).FullName} and {typeof(T).FullName} are not a type, Try .select().mapper().ToList"); } } } } @@ -909,7 +909,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, "{0} and {1} are not a type, Try .select().mapper().ToList", typeof(TResult).FullName, typeof(T).FullName); + { throw new SqlSugarException($"{typeof(TResult).FullName} and {typeof(T).FullName} are not a type, Try .select().mapper().ToList"); } } } } @@ -927,7 +927,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, "{0} and {1} are not a type, Try .select().mapper().ToList", typeof(TResult).FullName, typeof(T).FullName); + { throw new SqlSugarException($"{typeof(TResult).FullName} and {typeof(T).FullName} are not a type, Try .select().mapper().ToList"); } } } } @@ -949,13 +949,13 @@ namespace ThingsGateway.SqlSugar { mapperField = (mapperField as LambdaExpression).Body; } - Check.Exception(mapperObject is MemberExpression == false || mapperField is MemberExpression == false, ".Mapper() parameter error"); + if (mapperObject is MemberExpression == false || mapperField is MemberExpression == false) { throw new SqlSugarException(".Mapper() parameter error"); } var mapperObjectExp = mapperObject as MemberExpression; var mapperFieldExp = mapperField as MemberExpression; - Check.Exception(mapperFieldExp.Type.IsClass(), ".Mapper() parameter error"); + if (mapperFieldExp.Type.IsClass()) { throw new SqlSugarException(".Mapper() parameter error"); } var objType = mapperObjectExp.Type; var fieldType = mapperFieldExp.Expression.Type; - Check.Exception(objType != typeof(TObject) && objType != typeof(List), ".Mapper() parameter error"); + if (objType != typeof(TObject) && objType != typeof(List)) { throw new SqlSugarException(".Mapper() parameter error"); } if (objType == typeof(List)) { objType = typeof(TObject); @@ -992,7 +992,7 @@ namespace ThingsGateway.SqlSugar } if (whereCol == null) { - Check.Exception(true, ".Mapper() parameter error"); + { throw new SqlSugarException(".Mapper() parameter error"); } } var inValues = entitys.Select(it => it.GetType().GetProperty(fieldName).GetValue(it, null).ObjToString()); if (inValues?.Any() == true && UtilMethods.GetUnderType(entitys[0].GetType().GetProperty(fieldName).PropertyType) == UtilConstants.GuidType) @@ -1053,7 +1053,7 @@ namespace ThingsGateway.SqlSugar } if (whereCol == null) { - Check.Exception(true, ".Mapper() parameter error"); + { throw new SqlSugarException(".Mapper() parameter error"); } } var inValues = entitys.Select(it => it.GetType().GetProperty(whereCol.PropertyName).GetValue(it, null).ObjToString()); var dbColumnName = fieldEntity.Columns.FirstOrDefault(it => it.PropertyName == fieldName).DbColumnName; @@ -1113,15 +1113,15 @@ namespace ThingsGateway.SqlSugar { childField = (childField as LambdaExpression).Body; } - Check.Exception(mapperObject is MemberExpression == false || mainField is MemberExpression == false, ".Mapper() parameter error"); + if (mapperObject is MemberExpression == false || mainField is MemberExpression == false) { throw new SqlSugarException(".Mapper() parameter error"); } var mapperObjectExp = mapperObject as MemberExpression; var mainFieldExp = mainField as MemberExpression; var childFieldExp = childField as MemberExpression; - Check.Exception(mainFieldExp.Type.IsClass(), ".Mapper() parameter error"); - Check.Exception(childFieldExp.Type.IsClass(), ".Mapper() parameter error"); + if (mainFieldExp.Type.IsClass()) { throw new SqlSugarException(".Mapper() parameter error"); } + if (childFieldExp.Type.IsClass()) { throw new SqlSugarException(".Mapper() parameter error"); } var objType = mapperObjectExp.Type; var fieldType = mainFieldExp.Expression.Type; - Check.Exception(objType != typeof(TObject) && objType != typeof(List), ".Mapper() parameter error"); + if (objType != typeof(TObject) && objType != typeof(List)) { throw new SqlSugarException(".Mapper() parameter error"); } if (objType == typeof(List)) { objType = typeof(TObject); @@ -1159,7 +1159,7 @@ namespace ThingsGateway.SqlSugar } if (whereCol == null) { - Check.Exception(true, ".Mapper() parameter error"); + { throw new SqlSugarException(".Mapper() parameter error"); } } var inValues = entitys.Select(it => it.GetType().GetProperty(mainFieldName).GetValue(it, null).ObjToString()); List wheres = new List() @@ -1215,7 +1215,7 @@ namespace ThingsGateway.SqlSugar } if (whereCol == null) { - Check.Exception(true, ".Mapper() parameter error"); + { throw new SqlSugarException(".Mapper() parameter error"); } } var inValues = entitys.Select(it => it.GetType().GetProperty(whereCol.PropertyName).GetValue(it, null).ObjToString()); var dbColumnName = fieldEntity.Columns.FirstOrDefault(it => it.PropertyName == mainFieldName).DbColumnName; @@ -1321,7 +1321,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.ExceptionEasy($"OrderByPropertyName error.{orderPropertyName} does not exist in the entity class", $"OrderByPropertyName出错实体类中不存在{orderPropertyName}"); + Check.ExceptionLang($"OrderByPropertyName error.{orderPropertyName} does not exist in the entity class", $"OrderByPropertyName出错实体类中不存在{orderPropertyName}"); } } @@ -1601,7 +1601,7 @@ namespace ThingsGateway.SqlSugar this.QueryBuilder.SelectValue = this.SqlBuilder.GetTranslationColumnName(this.QueryBuilder.TableShortName) + ".*"; } } - Check.Exception(result.JoinIndex > 10, ErrorMessage.GetThrowMessage("只支持12个表", "Only 12 tables are supported")); + if (result.JoinIndex > 10) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("只支持12个表", "Only 12 tables are supported")); } return result; } protected ISugarQueryable _Select(Expression expression) @@ -1799,9 +1799,9 @@ namespace ThingsGateway.SqlSugar { if (this.QueryBuilder.JoinQueryInfos.Count(it => it.TableName.EqualCase(tableName)) > 1) { - Check.ExceptionEasy($"if same entity name ,.LeftJoin(db.Queryable<{entityName}>,(x,y..)=>....).AS(\"{tableName}\")", $"存在相同实体,请使用.LeftJoin(db.Queryable<{entityName}>).AS(\"{tableName}\",(x,y..)=>...)"); + Check.ExceptionLang($"if same entity name ,.LeftJoin(db.Queryable<{entityName}>,(x,y..)=>....).AS(\"{tableName}\")", $"存在相同实体,请使用.LeftJoin(db.Queryable<{entityName}>).AS(\"{tableName}\",(x,y..)=>...)"); } - Check.Exception(true, ErrorMessage.GetThrowMessage($"use AS<{tableName}>(\"{tableName}\")", $"请把 AS(\"{tableName}\"), 改成 AS<{tableName}实体>(\"{tableName}\")")); + { throw new SqlSugarException(ErrorMessage.GetThrowMessage($"use AS<{tableName}>(\"{tableName}\")", $"请把 AS(\"{tableName}\"), 改成 AS<{tableName}实体>(\"{tableName}\")")); } } else { @@ -2214,9 +2214,9 @@ namespace ThingsGateway.SqlSugar clone.QueryBuilder.AppendValues = null; clone.QueryBuilder.SubToListParameters = null; clone.QueryBuilder.AppendColumns = null; - Check.Exception(this.MapperAction != null || this.MapperActionWithCache != null, ErrorMessage.GetThrowMessage("'Mapper’ needs to be written after ‘MergeTable’ ", "Mapper 只能在 MergeTable 之后使用")); - //Check.Exception(this.QueryBuilder.SelectValue.IsNullOrEmpty(),ErrorMessage.GetThrowMessage( "MergeTable need to use Queryable.Select Method .", "使用MergeTable之前必须要有Queryable.Select方法")); - //Check.Exception(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0 || this.QueryBuilder.OrderByValue.HasValue(),ErrorMessage.GetThrowMessage( "MergeTable Queryable cannot Take Skip OrderBy PageToList ", "使用 MergeTable不能有 Take Skip OrderBy PageToList 等操作,你可以在Mergetable之后操作")); + if (this.MapperAction != null || this.MapperActionWithCache != null) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("'Mapper’ needs to be written after ‘MergeTable’ ", "Mapper 只能在 MergeTable 之后使用")); } + //if(this.QueryBuilder.SelectValue.IsNullOrEmpty()){throw new SqlSugarException(ErrorMessage.GetThrowMessage( "MergeTable need to use Queryable.Select Method .", "使用MergeTable之前必须要有Queryable.Select方法"));} + //if(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0 || this.QueryBuilder.OrderByValue.HasValue()){throw new SqlSugarException(ErrorMessage.GetThrowMessage( "MergeTable Queryable cannot Take Skip OrderBy PageToList ", "使用 MergeTable不能有 Take Skip OrderBy PageToList 等操作,你可以在Mergetable之后操作"));} var sqlobj = clone.ToSql(); var index = QueryBuilder.WhereIndex + 1; var result = this.Context.Queryable().AS(SqlBuilder.GetPackTable(sqlobj.Key, "MergeTable")).AddParameters(sqlobj.Value).Select("*").With(SqlWith.Null); @@ -2240,9 +2240,9 @@ namespace ThingsGateway.SqlSugar clone.QueryBuilder.AppendValues = null; clone.QueryBuilder.SubToListParameters = null; clone.QueryBuilder.AppendColumns = null; - Check.Exception(this.MapperAction != null || this.MapperActionWithCache != null, ErrorMessage.GetThrowMessage("'Mapper’ needs to be written after ‘MergeTable’ ", "Mapper 只能在 MergeTable 之后使用")); - //Check.Exception(this.QueryBuilder.SelectValue.IsNullOrEmpty(),ErrorMessage.GetThrowMessage( "MergeTable need to use Queryable.Select Method .", "使用MergeTable之前必须要有Queryable.Select方法")); - //Check.Exception(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0 || this.QueryBuilder.OrderByValue.HasValue(),ErrorMessage.GetThrowMessage( "MergeTable Queryable cannot Take Skip OrderBy PageToList ", "使用 MergeTable不能有 Take Skip OrderBy PageToList 等操作,你可以在Mergetable之后操作")); + if (this.MapperAction != null || this.MapperActionWithCache != null) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("'Mapper’ needs to be written after ‘MergeTable’ ", "Mapper 只能在 MergeTable 之后使用")); } + //if(this.QueryBuilder.SelectValue.IsNullOrEmpty()){throw new SqlSugarException(ErrorMessage.GetThrowMessage( "MergeTable need to use Queryable.Select Method .", "使用MergeTable之前必须要有Queryable.Select方法"));} + //if(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0 || this.QueryBuilder.OrderByValue.HasValue()){throw new SqlSugarException(ErrorMessage.GetThrowMessage( "MergeTable Queryable cannot Take Skip OrderBy PageToList ", "使用 MergeTable不能有 Take Skip OrderBy PageToList 等操作,你可以在Mergetable之后操作"));} var sqlobj = clone.ToSql(); var index = QueryBuilder.WhereIndex + 1; var result = this.Context.Queryable().AS(SqlBuilder.GetPackTable(sqlobj.Key, "MergeTable")).AddParameters(sqlobj.Value).Select("*").With(SqlWith.Null); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableProvider.cs index b8aa45bf7..11392546e 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/QueryableProvider/QueryableProvider.cs @@ -461,12 +461,12 @@ namespace ThingsGateway.SqlSugar //A var aEntity = this.Context.EntityMaintenance.GetEntityInfo(aType); var aPropertyName = aEntity.Columns.FirstOrDefault(it => it.IsPrimarykey == true)?.PropertyName; - Check.Exception(aPropertyName == null, aEntity.EntityName + " no primary key"); + if (aPropertyName == null) { throw new SqlSugarException($"{aEntity.EntityName} no primary key"); } //B var bEntity = this.Context.EntityMaintenance.GetEntityInfo(bType); var bProperty = bEntity.Columns.FirstOrDefault(it => it.IsPrimarykey == true)?.PropertyName; - Check.Exception(bProperty == null, bEntity.EntityName + " no primary key"); + if (bProperty == null) { throw new SqlSugarException($"{bEntity.EntityName} no primary key"); } var bDbField = bEntity.Columns.FirstOrDefault(it => it.IsPrimarykey == true).DbColumnName; this.Mapper((it, cache) => { @@ -535,7 +535,7 @@ namespace ThingsGateway.SqlSugar } public ISugarQueryable Mapper(Expression> mapperObject, Expression> mainField, Expression> childField) { - Check.Exception(mapperObject.ReturnType.Name == "IList`1", "Mapper no support IList , Use List"); + if (mapperObject.ReturnType.Name == "IList`1") { throw new SqlSugarException("Mapper no support IList , Use List"); } if (CallContext.MapperExpression.Value == null) { CallContext.MapperExpression.Value = new List(); @@ -549,7 +549,7 @@ namespace ThingsGateway.SqlSugar } public virtual ISugarQueryable Mapper(Expression>> mapperObject, Expression> mapperField) { - Check.Exception(mapperObject.ReturnType.Name == "IList`1", "Mapper no support IList , Use List"); + if (mapperObject.ReturnType.Name == "IList`1") { throw new SqlSugarException("Mapper no support IList , Use List"); } if (CallContext.MapperExpression.Value == null) { CallContext.MapperExpression.Value = new List(); @@ -663,8 +663,8 @@ namespace ThingsGateway.SqlSugar public ISugarQueryable TranLock(DbLockType? LockType = DbLockType.Wait) { if (LockType == null) return this; - Check.ExceptionEasy(this.Context.Ado.Transaction == null, "need BeginTran", "需要事务才能使用TranLock"); - Check.ExceptionEasy(this.QueryBuilder.IsSingle() == false, "TranLock, can only be used for single table query", "TranLock只能用在单表查询"); + if (this.Context.Ado.Transaction == null) { throw new SqlSugarLangException("need BeginTran", "需要事务才能使用TranLock"); } + if (this.QueryBuilder.IsSingle() == false) { throw new SqlSugarLangException("TranLock, can only be used for single table query", "TranLock只能用在单表查询"); } if (this.Context.CurrentConnectionConfig.DbType == DbType.SqlServer) { if (LockType == DbLockType.Wait) @@ -748,8 +748,8 @@ namespace ThingsGateway.SqlSugar if (whereClassTypes.HasValue()) { var columns = this.Context.EntityMaintenance.GetEntityInfo().Columns.Where(it => it.IsIgnore == false && it.IsPrimarykey == true); - Check.Exception(columns?.Any() != true, "{0} no primary key, Can not use WhereClassByPrimaryKey ", typeof(T).Name); - Check.Exception(this.QueryBuilder.IsSingle() == false, "No support join query"); + if (columns?.Any() != true) { throw new SqlSugarException("{typeof(T).Name} no primary key, Can not use WhereClassByPrimaryKey "); } + if (this.QueryBuilder.IsSingle() == false) { throw new SqlSugarException("No support join query"); } List whereModels = new List(); foreach (var item in whereClassTypes) { @@ -818,8 +818,8 @@ namespace ThingsGateway.SqlSugar if (whereClassTypes.HasValue()) { var columns = this.Context.EntityMaintenance.GetEntityInfo().Columns.Where(it => whereColumns.Contains(it.PropertyName) || whereColumns.Contains(it.DbColumnName)); - Check.Exception(columns?.Any() != true, "{0} no primary key, Can not use whereColumns ", typeof(T).Name); - Check.Exception(this.QueryBuilder.IsSingle() == false, "No support join query"); + if (columns?.Any() != true) { throw new SqlSugarException("{ typeof(T).Name} no primary key, Can not use whereColumns "); } + if (this.QueryBuilder.IsSingle() == false) { throw new SqlSugarException("No support join query"); } List whereModels = new List(); foreach (var item in whereClassTypes) { @@ -1067,7 +1067,7 @@ namespace ThingsGateway.SqlSugar { pkValue = -1; } - Check.Exception(this.QueryBuilder.SelectValue.HasValue(), "'InSingle' and' Select' can't be used together,You can use .Select(it=>...).Single(it.id==1)"); + if (this.QueryBuilder.SelectValue.HasValue()) { throw new SqlSugarException("'InSingle' and' Select' can't be used together,You can use .Select(it=>...).Single(it.id==1)"); } var list = In([pkValue]).ToList(); if (list == null) return default(T); else return list.SingleOrDefault(); @@ -1108,7 +1108,7 @@ namespace ThingsGateway.SqlSugar return In(newValues); } var pks = GetPrimaryKeys().Select(it => SqlBuilder.GetTranslationTableName(it)).ToList(); - Check.Exception(pks == null || pks.Count != 1, "Queryable.In(params object[] pkValues): Only one primary key"); + if (pks == null || pks.Count != 1) { throw new SqlSugarException("Queryable.In(params object[] pkValues): Only one primary key"); } string field = pks.FirstOrDefault(); string shortName = QueryBuilder.TableShortName == null ? null : (QueryBuilder.TableShortName + "."); field = shortName + field; @@ -1277,7 +1277,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.ExceptionEasy($"OrderByPropertyName error.{orderPropertyName} does not exist in the entity class", $"OrderByPropertyName出错实体类中不存在{orderPropertyName}"); + Check.ExceptionLang($"OrderByPropertyName error.{orderPropertyName} does not exist in the entity class", $"OrderByPropertyName出错实体类中不存在{orderPropertyName}"); } } return this; @@ -1516,7 +1516,7 @@ namespace ThingsGateway.SqlSugar { if (typeof(TResult).IsInterface && this.QueryBuilder.AsType == null) { - Check.ExceptionEasy("Select< interface > requires a full example of AsType(type) db.Queryable().AsType(type).Select().ToList()" + Check.ExceptionLang("Select< interface > requires a full example of AsType(type) db.Queryable().AsType(type).Select().ToList()" , "Select<接口>需要AsType(type)完整示例db.Queryable().AsType(type).Select().ToList()"); } if (this.QueryBuilder.SelectValue.HasValue() && this.QueryBuilder.SelectValue.ObjToString().Contains(nameof(QueryMethodInfo.AS))) @@ -1611,9 +1611,9 @@ namespace ThingsGateway.SqlSugar { return MergeTableWithSubToList(); } - Check.Exception(this.MapperAction != null || this.MapperActionWithCache != null, ErrorMessage.GetThrowMessage("'Mapper’ needs to be written after ‘MergeTable’ ", "Mapper 只能在 MergeTable 之后使用")); - //Check.Exception(this.QueryBuilder.SelectValue.IsNullOrEmpty(),ErrorMessage.GetThrowMessage( "MergeTable need to use Queryable.Select Method .", "使用MergeTable之前必须要有Queryable.Select方法")); - //Check.Exception(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0 || this.QueryBuilder.OrderByValue.HasValue(),ErrorMessage.GetThrowMessage( "MergeTable Queryable cannot Take Skip OrderBy PageToList ", "使用 MergeTable不能有 Take Skip OrderBy PageToList 等操作,你可以在Mergetable之后操作")); + if (this.MapperAction != null || this.MapperActionWithCache != null) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("'Mapper’ needs to be written after ‘MergeTable’ ", "Mapper 只能在 MergeTable 之后使用")); } + //if(this.QueryBuilder.SelectValue.IsNullOrEmpty()){throw new SqlSugarException(ErrorMessage.GetThrowMessage( "MergeTable need to use Queryable.Select Method .", "使用MergeTable之前必须要有Queryable.Select方法"));} + //if(this.QueryBuilder.Skip > 0 || this.QueryBuilder.Take > 0 || this.QueryBuilder.OrderByValue.HasValue()){throw new SqlSugarException(ErrorMessage.GetThrowMessage( "MergeTable Queryable cannot Take Skip OrderBy PageToList ", "使用 MergeTable不能有 Take Skip OrderBy PageToList 等操作,你可以在Mergetable之后操作"));} var sqlobj = this._ToSql(); if (IsSubToList()) { @@ -1648,14 +1648,14 @@ namespace ThingsGateway.SqlSugar { UtilMethods.StartCustomSplitTable(this.Context, typeof(T)); var splitColumn = this.EntityInfo.Columns.FirstOrDefault(it => it.PropertyInfo.GetCustomAttribute() != null); - Check.ExceptionEasy(splitColumn == null, "[SplitFieldAttribute] need to be added to the table field", "需要在分表字段加上属性[SplitFieldAttribute]"); + if (splitColumn == null) { throw new SqlSugarLangException("[SplitFieldAttribute] need to be added to the table field", "需要在分表字段加上属性[SplitFieldAttribute]"); } var columnName = this.SqlBuilder.GetTranslationColumnName(splitColumn.DbColumnName); var sqlParameterKeyWord = this.SqlBuilder.SqlParameterKeyWord; var resultQueryable = this.Where($" {columnName}>={sqlParameterKeyWord}spBeginTime AND {columnName}<= {sqlParameterKeyWord}spEndTime", new { spBeginTime = beginTime, spEndTime = endTime }).SplitTable(tas => { var result = tas; var type = this.EntityInfo.Type.GetCustomAttribute(); - Check.ExceptionEasy(type == null, $"{this.EntityInfo.EntityName}need SplitTableAttribute", $"{this.EntityInfo.EntityName}需要特性 SplitTableAttribute"); + if (type == null) { throw new SqlSugarLangException($"{this.EntityInfo.EntityName}need SplitTableAttribute", $"{this.EntityInfo.EntityName}需要特性 SplitTableAttribute"); } if (SplitType.Month == type.SplitType) { result = result.Where(y => y.Date >= beginTime.ToString("yyyy-MM").ObjToDate() && y.Date <= endTime.Date.ToString("yyyy-MM").ObjToDate().AddMonths(1).AddDays(-1)).ToList(); @@ -1680,8 +1680,13 @@ namespace ThingsGateway.SqlSugar } else if (SplitType.Season == type.SplitType) { - var beginSeason = Convert.ToDateTime(beginTime.AddMonths(0 - ((beginTime.Month - 1) % 3)).ToString("yyyy-MM-01")).Date; - var endSeason = DateTime.Parse(endTime.AddMonths(3 - ((endTime.Month - 1) % 3)).ToString("yyyy-MM-01")).AddDays(-1).Date; + var beginSeason = new DateTime(beginTime.Year, beginTime.Month - (beginTime.Month - 1) % 3, 1); + + var endQuarterStartMonth = endTime.Month - (endTime.Month - 1) % 3; + var endSeason = new DateTime(endTime.Year, endQuarterStartMonth, 1) + .AddMonths(3) + .AddDays(-1); + result = result.Where(y => y.Date >= beginSeason && y.Date <= endSeason).ToList(); } @@ -1750,7 +1755,7 @@ namespace ThingsGateway.SqlSugar public ISugarQueryable WithCache(string cacheKey, int cacheDurationInSeconds = int.MaxValue) { cacheDurationInSeconds = SetCacheTime(cacheDurationInSeconds); - Check.ArgumentNullException(this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService, "Use Cache ConnectionConfig.ConfigureExternalServices.DataInfoCacheService is required "); + if (this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService == null) { throw new SqlSugarException("Use Cache ConnectionConfig.ConfigureExternalServices.DataInfoCacheService is required "); } this.IsCache = true; this.CacheTime = cacheDurationInSeconds; this.CacheKey = cacheKey; @@ -1759,7 +1764,7 @@ namespace ThingsGateway.SqlSugar public ISugarQueryable WithCache(int cacheDurationInSeconds = int.MaxValue) { cacheDurationInSeconds = SetCacheTime(cacheDurationInSeconds); - Check.ArgumentNullException(this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService, "Use Cache ConnectionConfig.ConfigureExternalServices.DataInfoCacheService is required "); + if (this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService == null) { throw new SqlSugarException("Use Cache ConnectionConfig.ConfigureExternalServices.DataInfoCacheService is required "); } this.IsCache = true; this.CacheTime = cacheDurationInSeconds; return this; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/SaveableProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/SaveableProvider.cs index 3bf3858a3..fc823d120 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/SaveableProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/SaveableProvider.cs @@ -27,8 +27,8 @@ namespace ThingsGateway.SqlSugar this.Context.Ado.IsDisableMasterSlaveSeparation = true; List result = new List(); var pks = GetPrimaryKeys(); - Check.Exception(pks.IsNullOrEmpty(), "Need primary key"); - Check.Exception(pks.Count > 1, "Multiple primary keys are not supported"); + if (pks.IsNullOrEmpty()) { throw new SqlSugarException("Need primary key"); } + if (pks.Count > 1) { throw new SqlSugarException("Multiple primary keys are not supported"); } var pkInfo = this.EntityInfo.Columns.Where(it => it.IsIgnore == false && it.DbColumnName.Equals(pks[0], StringComparison.CurrentCultureIgnoreCase)).First(); var pkValues = saveObjects.Select(it => it.GetType().GetProperty(pkInfo.PropertyName).GetValue(it, null)); if (existsObjects == null) @@ -49,8 +49,8 @@ namespace ThingsGateway.SqlSugar this.Context.Ado.IsDisableMasterSlaveSeparation = true; List result = new List(); var pks = GetPrimaryKeys(); - Check.Exception(pks.IsNullOrEmpty(), "Need primary key"); - Check.Exception(pks.Count > 1, "Multiple primary keys are not supported"); + if (pks.IsNullOrEmpty()) { throw new SqlSugarException("Need primary key"); } + if (pks.Count > 1) { throw new SqlSugarException("Multiple primary keys are not supported"); } var pkInfo = this.EntityInfo.Columns.Where(it => it.IsIgnore == false && it.DbColumnName.Equals(pks[0], StringComparison.CurrentCultureIgnoreCase)).First(); var pkValues = saveObjects.Select(it => it.GetType().GetProperty(pkInfo.PropertyName).GetValue(it, null)); if (existsObjects == null) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/Storageable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/Storageable.cs index 755a50e2b..e7f0a8089 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/Storageable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/Storageable.cs @@ -100,7 +100,7 @@ namespace ThingsGateway.SqlSugar { if (PageSize > 10000) { - Check.ExceptionEasy("Advanced save page Settings should not exceed 10,000, and the reasonable number of pages is about 2000", "高级保存分页设置不要超过1万,合理分页数在2000左右"); + Check.ExceptionLang("Advanced save page Settings should not exceed 10,000, and the reasonable number of pages is about 2000", "高级保存分页设置不要超过1万,合理分页数在2000左右"); } StorageablePage page = new StorageablePage(); page.Context = this.Context; @@ -125,7 +125,7 @@ namespace ThingsGateway.SqlSugar public IStorageable DefaultAddElseUpdate() { var column = this.Context.EntityMaintenance.GetEntityInfo().Columns.FirstOrDefault(it => it.IsPrimarykey); - if (column == null) Check.ExceptionEasy("DefaultAddElseUpdate() need primary key", "DefaultAddElseUpdate()这个方法只能用于主键"); + if (column == null) Check.ExceptionLang("DefaultAddElseUpdate() need primary key", "DefaultAddElseUpdate()这个方法只能用于主键"); return this.SplitUpdate(it => { var itemPkValue = column.PropertyInfo.GetValue(it.Item); @@ -226,7 +226,7 @@ namespace ThingsGateway.SqlSugar var pkInfos = this.Context.EntityMaintenance.GetEntityInfo().Columns.Where(it => it.IsPrimarykey).ToArray(); if (whereExpression == null && pkInfos.Length == 0) { - Check.ExceptionEasy(true, "Need primary key or WhereColumn", "使用Storageable实体需要主键或者使用WhereColumn指定条件列"); + if (true) { throw new SqlSugarLangException("Need primary key or WhereColumn", "使用Storageable实体需要主键或者使用WhereColumn指定条件列"); } } if (whereExpression == null && pkInfos.Length != 0) { @@ -243,15 +243,15 @@ namespace ThingsGateway.SqlSugar Database = dbDataList, PkFields = pkProperties }).ToList(); - foreach (var item in whereFuncs.OrderByDescending(it => (int)it.key)) + foreach (var item in whereFuncs.OrderByDescending(it => (int)it.Key)) { var whereList = messageList.Where(it => it.StorageType == null); - Func, bool> exp = item.value1; + Func, bool> exp = item.Value; var list = whereList.Where(exp).ToList(); foreach (var it in list) { - it.StorageType = item.key; - it.StorageMessage = item.value2; + it.StorageType = item.Key; + it.StorageMessage = item.Value2; } } var delete = messageList.Where(it => it.StorageType == StorageType.Delete).ToList(); @@ -315,7 +315,7 @@ namespace ThingsGateway.SqlSugar var pkInfos = this.Context.EntityMaintenance.GetEntityInfo().Columns.Where(it => it.IsPrimarykey).ToArray(); if (whereExpression == null && pkInfos.Length == 0) { - Check.ExceptionEasy(true, "Need primary key or WhereColumn", "使用Storageable实体需要主键或者使用WhereColumn指定条件列"); + if (true) { throw new SqlSugarLangException("Need primary key or WhereColumn", "使用Storageable实体需要主键或者使用WhereColumn指定条件列"); } } if (whereExpression == null && pkInfos.Length != 0) { @@ -332,15 +332,15 @@ namespace ThingsGateway.SqlSugar Database = dbDataList, PkFields = pkProperties }).ToList(); - foreach (var item in whereFuncs.OrderByDescending(it => (int)it.key)) + foreach (var item in whereFuncs.OrderByDescending(it => (int)it.Key)) { var whereList = messageList.Where(it => it.StorageType == null); - Func, bool> exp = item.value1; + Func, bool> exp = item.Value; var list = whereList.Where(exp).ToList(); foreach (var it in list) { - it.StorageType = item.key; - it.StorageMessage = item.value2; + it.StorageType = item.Key; + it.StorageMessage = item.Value2; } } var delete = messageList.Where(it => it.StorageType == StorageType.Delete).ToList(); @@ -397,7 +397,7 @@ namespace ThingsGateway.SqlSugar var pkInfos = this.Context.EntityMaintenance.GetEntityInfo().Columns.Where(it => it.IsPrimarykey).ToArray(); if (whereExpression == null && pkInfos.Length == 0) { - Check.Exception(true, "Need primary key or WhereColumn"); + { throw new SqlSugarException("Need primary key or WhereColumn"); } } if (whereExpression == null && pkInfos.Length != 0) { @@ -414,15 +414,15 @@ namespace ThingsGateway.SqlSugar Database = dbDataList, PkFields = pkProperties }).ToList(); - foreach (var item in whereFuncs.OrderByDescending(it => (int)it.key)) + foreach (var item in whereFuncs.OrderByDescending(it => (int)it.Key)) { var whereList = messageList.Where(it => it.StorageType == null); - Func, bool> exp = item.value1; + Func, bool> exp = item.Value; var list = whereList.Where(exp).ToList(); foreach (var it in list) { - it.StorageType = item.key; - it.StorageMessage = item.value2; + it.StorageType = item.Key; + it.StorageMessage = item.Value2; } } var delete = messageList.Where(it => it.StorageType == StorageType.Delete).ToList(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableDataTable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableDataTable.cs index 5b4dda26f..23f6e8fc1 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableDataTable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableDataTable.cs @@ -32,7 +32,7 @@ namespace ThingsGateway.SqlSugar { this.Columns = names; var queryable = this.Context.Queryable(); - Check.Exception(Columns == null || Columns.Count == 0, "need WhereColumns"); + if (Columns == null || Columns.Count == 0) { throw new SqlSugarException("need WhereColumns"); } var tableName = queryable.SqlBuilder.GetTranslationTableName(DataTable.TableName); this.Context.Utilities.PageEach(DataTable.Rows.Cast(), 200, itemList => { @@ -91,9 +91,9 @@ namespace ThingsGateway.SqlSugar } foreach (DataRow row in DataTable.Rows) { - foreach (var item in whereFuncs.OrderByDescending(it => (int)it.key)) + foreach (var item in whereFuncs.OrderByDescending(it => (int)it.Key)) { - SplitMethod(item.value1, item.key, row, item.value2); + SplitMethod(item.Value, item.Key, row, item.Value2); } if (row[SugarGroupId] == null || row[SugarGroupId] == DBNull.Value) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableSplitProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableSplitProvider.cs index e30524322..d6349fa35 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableSplitProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SaveableProvider/StorageableSplitProvider.cs @@ -153,7 +153,7 @@ namespace ThingsGateway.SqlSugar private IEnumerable GroupDataList(IEnumerable datas) { var attribute = typeof(T).GetCustomAttribute() as SplitTableAttribute; - Check.Exception(attribute == null, $"{typeof(T).Name} need SplitTableAttribute"); + if (attribute == null) { throw new SqlSugarException($"{typeof(T).Name} need SplitTableAttribute"); } var db = this.Context; var context = db.SplitHelper(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/InsertBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/InsertBuilder.cs index 303261fce..0acd27e1b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/InsertBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/InsertBuilder.cs @@ -231,7 +231,7 @@ namespace ThingsGateway.SqlSugar { date = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig); } - return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"; + return $"'{date.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)}'"; } else if (type == UtilConstants.ByteArrayType) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/QueryBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/QueryBuilder.cs index cffb6c787..6b2f5314b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/QueryBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/QueryBuilder.cs @@ -286,12 +286,12 @@ namespace ThingsGateway.SqlSugar { if (this.TableShortName?.StartsWith('\"') == true) { - Check.Exception(!string.IsNullOrEmpty(this.TableShortName) && resolveExpress.SingleTableNameSubqueryShortName != this.TableShortName.TrimEnd('\"').TrimStart('\"'), "{0} and {1} need same name", resolveExpress.SingleTableNameSubqueryShortName, this.TableShortName); + if (!string.IsNullOrEmpty(this.TableShortName) && resolveExpress.SingleTableNameSubqueryShortName != this.TableShortName.TrimEnd('\"').TrimStart('\"')) { throw new SqlSugarException("{0} and {1} need same name", resolveExpress.SingleTableNameSubqueryShortName, this.TableShortName); } this.TableShortName = resolveExpress.SingleTableNameSubqueryShortName; } else { - Check.Exception(!string.IsNullOrEmpty(this.TableShortName) && resolveExpress.SingleTableNameSubqueryShortName != this.TableShortName, "{0} and {1} need same name", resolveExpress.SingleTableNameSubqueryShortName, this.TableShortName); + if (!string.IsNullOrEmpty(this.TableShortName) && resolveExpress.SingleTableNameSubqueryShortName != this.TableShortName) { throw new SqlSugarException("{0} and {1} need same name", resolveExpress.SingleTableNameSubqueryShortName, this.TableShortName); } this.TableShortName = resolveExpress.SingleTableNameSubqueryShortName; } } @@ -778,7 +778,7 @@ namespace ThingsGateway.SqlSugar } else if (this.EasyJoinInfos != null && this.EasyJoinInfos.Count != 0) { - Check.ExceptionEasy("No Supprt Subquery.ToList(), Inner Join Or Left Join", "Subquery.ToList请使用Inner方式联表"); + Check.ExceptionLang("No Supprt Subquery.ToList(), Inner Join Or Left Join", "Subquery.ToList请使用Inner方式联表"); } if (this.TableShortName == null) { @@ -1131,7 +1131,7 @@ namespace ThingsGateway.SqlSugar var index = currentParameters.IndexOf(item); var name = item.Name; var joinName = jsoinParameters[index].Name; - Check.Exception(!name.Equals(joinName, StringComparison.CurrentCultureIgnoreCase), ErrorMessage.ExpressionCheck, joinName, methodName, name); + if (!name.Equals(joinName, StringComparison.CurrentCultureIgnoreCase)) { throw new SqlSugarException(ErrorMessage.ExpressionCheck, joinName, methodName, name); } } } } @@ -1159,7 +1159,7 @@ namespace ThingsGateway.SqlSugar var index = currentParameters.IndexOf(item); var name = item.Name; var joinName = jsoinParameters[index].Name; - Check.Exception(!name.Equals(joinName, StringComparison.CurrentCultureIgnoreCase), ErrorMessage.ExpressionCheck, joinName, methodName, name); + if (!name.Equals(joinName, StringComparison.CurrentCultureIgnoreCase)) { throw new SqlSugarException(ErrorMessage.ExpressionCheck, joinName, methodName, name); } } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider.cs index 5e38b20a2..407cc5b7e 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider.cs @@ -37,7 +37,7 @@ namespace ThingsGateway.SqlSugar } public virtual string GetTranslationTableName(string name) { - Check.ArgumentNullException(name, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (name == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } if (!name.Contains("<>f__AnonymousType") && name.IsContainsIn("(", ")", SqlTranslationLeft) && name != "Dictionary`2") { var tableInfo = this.Context @@ -73,8 +73,8 @@ namespace ThingsGateway.SqlSugar } public virtual string GetTranslationColumnName(string entityName, string propertyName) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); - Check.ArgumentNullException(propertyName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } + if (propertyName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } var context = this.Context; var mappingInfo = context .MappingColumns diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider_Condition.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider_Condition.cs index 6d10fd18e..ca1cdf19a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider_Condition.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/SqlBuilderProvider_Condition.cs @@ -203,7 +203,7 @@ namespace ThingsGateway.SqlSugar var valueArray = (value + "").Split(','); if (valueArray.Length != 2) { - Check.ExceptionEasy($"The {item.FieldName} value is not a valid format, but is properly separated by a comma (1,2)", $"{item.FieldName} 值不是有效格式,正确是 1,2 这种中间逗号隔开"); + Check.ExceptionLang($"The {item.FieldName} value is not a valid format, but is properly separated by a comma (1,2)", $"{item.FieldName} 值不是有效格式,正确是 1,2 这种中间逗号隔开"); } var firstValue = GetFieldValue(new ConditionalModel() { CSharpTypeName = item.CSharpTypeName, FieldValue = valueArray.FirstOrDefault() }); var lastValue = GetFieldValue(new ConditionalModel() { CSharpTypeName = item.CSharpTypeName, FieldValue = valueArray.LastOrDefault() }); @@ -219,7 +219,7 @@ namespace ThingsGateway.SqlSugar var valueArray = (value + "").Split(','); if (valueArray.Length != 2) { - Check.ExceptionEasy($"The {item.FieldName} value is not a valid format, but is properly separated by a comma (1,2)", $"{item.FieldName} 值不是有效格式,正确是 1,2 这种中间逗号隔开"); + Check.ExceptionLang($"The {item.FieldName} value is not a valid format, but is properly separated by a comma (1,2)", $"{item.FieldName} 值不是有效格式,正确是 1,2 这种中间逗号隔开"); } var times = GetDateRange(valueArray.FirstOrDefault(), valueArray.LastOrDefault()); var parameterNameFirst = parameterName + "_01"; @@ -250,10 +250,10 @@ namespace ThingsGateway.SqlSugar date2Str = date2Str + ":00:00"; } if (!DateTime.TryParse(date1Str, out var date1)) - Check.ExceptionEasy("date1 format is incorrect.(yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm |yyyy-MM-dd HH:mm:ss)", "date1 格式不正确,支持格式 yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm|yyyy-MM-dd HH:mm:ss"); + Check.ExceptionLang("date1 format is incorrect.(yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm |yyyy-MM-dd HH:mm:ss)", "date1 格式不正确,支持格式 yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm|yyyy-MM-dd HH:mm:ss"); if (!DateTime.TryParse(date2Str, out var date2)) - Check.ExceptionEasy("date2 format is incorrect.", "date2 格式不正确"); + Check.ExceptionLang("date2 format is incorrect.", "date2 格式不正确"); if (len == 4) // yyyy date2 = date2.AddYears(1); @@ -268,7 +268,7 @@ namespace ThingsGateway.SqlSugar else if (len == 19) // yyyy-MM-dd HH:mm date2 = date2.AddSeconds(1); else - Check.ExceptionEasy("date format is incorrect.(yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm|yyyy-MM-dd HH:mm:ss)", "date 格式不正确,支持格式 yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm|yyyy-MM-dd HH:mm:ss"); + Check.ExceptionLang("date format is incorrect.(yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm|yyyy-MM-dd HH:mm:ss)", "date 格式不正确,支持格式 yyyy-MM-dd | yyyy | yyyy-MM | yyyy-MM-dd HH | yyyy-MM-dd HH:mm|yyyy-MM-dd HH:mm:ss"); return new DateTime[] { date1, date2 }; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/UpdateBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/UpdateBuilder.cs index 4e924e3d4..408b2839c 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/UpdateBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SqlBuilderProvider/UpdateBuilder.cs @@ -192,7 +192,7 @@ namespace ThingsGateway.SqlSugar protected virtual string TomultipleSqlString(List> groupList) { - Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + if (PrimaryKeys == null || PrimaryKeys.Count == 0) { throw new SqlSugarException(" Update List need Primary key"); } int pageSize = 200; int pageIndex = 1; int totalRecord = groupList.Count; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarAccessory.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarAccessory.cs index d72d540fb..00b531702 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarAccessory.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarAccessory.cs @@ -261,7 +261,7 @@ namespace ThingsGateway.SqlSugar protected ISugarQueryable CreateQueryable(ISugarQueryable result) { this.SugarActionType = SugarActionType.Query; - Check.Exception(typeof(T).IsClass() == false || typeof(T).GetConstructors().Length == 0, "Queryable<{0}> Error ,{0} is invalid , need is a class,and can new().", typeof(T).Name); + if (typeof(T).IsClass() == false || typeof(T).GetConstructors().Length == 0) { throw new SqlSugarException("Queryable<{0}> Error ,{0} is invalid , need is a class,and can new().", typeof(T).Name); } var sqlBuilder = InstanceFactory.GetSqlbuilder(CurrentConnectionConfig); result.Context = this.Context; result.SqlBuilder = sqlBuilder; @@ -468,30 +468,30 @@ namespace ThingsGateway.SqlSugar // InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.Access" : "SqlSugar.AccessCore"; // break; case DbType.Custom: - Check.Exception(InstanceFactory.CustomDbName.IsNullOrEmpty(), "DbType.Custom: InstanceFactory.CustomDbName is not null "); - Check.Exception(InstanceFactory.CustomNamespace.IsNullOrEmpty(), "DbType.Custom: InstanceFactory.CustomNamespace is not null "); - Check.Exception(InstanceFactory.CustomDllName.IsNullOrEmpty(), "DbType.Custom: InstanceFactory.CustomDllName is not null "); + if (InstanceFactory.CustomDbName.IsNullOrEmpty()) { throw new SqlSugarException("DbType.Custom: InstanceFactory.CustomDbName is not null "); } + if (InstanceFactory.CustomNamespace.IsNullOrEmpty()) { throw new SqlSugarException("DbType.Custom: InstanceFactory.CustomNamespace is not null "); } + if (InstanceFactory.CustomDllName.IsNullOrEmpty()) { throw new SqlSugarException("DbType.Custom: InstanceFactory.CustomDllName is not null "); } break; case DbType.QuestDB: DependencyManagement.TryPostgreSQL(); break; //case DbType.ClickHouse: - // Check.Exception(SugarCompatible.IsFramework, "ClickHouse only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("ClickHouse only support .net core");} // InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.ClickHouse" : "SqlSugar.ClickHouseCore"; // break; //case DbType.GBase: - // Check.Exception(SugarCompatible.IsFramework, "GBase only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("GBase only support .net core");} // InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.GBase" : "SqlSugar.GBaseCore"; // break; //case DbType.Odbc: // InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.Odbc" : "SqlSugar.OdbcCore"; // break; //case DbType.OceanBaseForOracle: - // Check.Exception(SugarCompatible.IsFramework, "OceanBaseForOracle only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("OceanBaseForOracle only support .net core");} // InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.OceanBaseForOracle" : "SqlSugar.OceanBaseForOracleCore"; // break; //case DbType.TDSQLForPGODBC: - // Check.Exception(SugarCompatible.IsFramework, "TDSQLForPGODBC only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("TDSQLForPGODBC only support .net core");} // InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.TDSQLForPGODBC" : "SqlSugar.TDSQLForPGODBC"; // break; case DbType.GaussDB: @@ -533,15 +533,15 @@ namespace ThingsGateway.SqlSugar break; case DbType.TDengine: config.DbType = DbType.TDengine; - //Check.Exception(SugarCompatible.IsFramework, "TDengine only support .net core"); + //if(SugarCompatible.IsFramework){throw new SqlSugarException("TDengine only support .net core");} //InstanceFactory.CustomDllName = SugarCompatible.IsFramework ? "SqlSugar.TDengine" : "SqlSugar.TDengineCore"; break; //case DbType.HANA: - // Check.Exception(SugarCompatible.IsFramework, "NANA only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("NANA only support .net core");} // InstanceFactory.CustomDllName = "SqlSugar.HANAConnector"; // break; //case DbType.Xugu: - // Check.Exception(SugarCompatible.IsFramework, "Xugu only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("Xugu only support .net core");} // //InstanceFactory.CustomDbName = "Xugu"; // InstanceFactory.CustomDllName = "SqlSugar.XuguCore"; // //InstanceFactory.CustomNamespace = "SqlSugar.Xugu"; @@ -550,11 +550,11 @@ namespace ThingsGateway.SqlSugar config.DbType = DbType.MySql; break; //case DbType.DB2: - // Check.Exception(SugarCompatible.IsFramework, "Db2 only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("Db2 only support .net core");} // InstanceFactory.CustomDllName = "SqlSugar.Db2Core"; // break; //case DbType.GaussDBNative: - // Check.Exception(SugarCompatible.IsFramework, "GaussDBNative only support .net core"); + // if(SugarCompatible.IsFramework){throw new SqlSugarException("GaussDBNative only support .net core");} // InstanceFactory.CustomDllName = "SqlSugar.GaussDBCore"; // break; //case DbType.DuckDB: diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarProvider.cs index 65068b098..5ea7d9b20 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarProvider.cs @@ -19,7 +19,7 @@ namespace ThingsGateway.SqlSugar this.Context = this; this.CurrentConnectionConfig = config; this.ContextID = Guid.NewGuid(); - Check.ArgumentNullException(config, "config is null"); + if (config == null) { throw new SqlSugarException("config is null"); } CheckDbDependency(config); if (StaticConfig.CompleteDbFunc != null) { @@ -130,7 +130,7 @@ namespace ThingsGateway.SqlSugar /// public virtual ISugarQueryable Queryable(string shortName) { - Check.Exception(shortName.HasValue() && shortName.Length > 40, ErrorMessage.GetThrowMessage("shortName参数长度不能超过40,你可能是想用这个方法 db.SqlQueryable(sql)而不是db.Queryable(shortName)", "Queryable.shortName max length 20")); + if (shortName.HasValue() && shortName.Length > 40) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("shortName参数长度不能超过40,你可能是想用这个方法 db.SqlQueryable(sql)而不是db.Queryable(shortName)", "Queryable.shortName max length 20")); } var queryable = Queryable(); queryable.SqlBuilder.QueryBuilder.TableShortName = shortName; return queryable; @@ -456,8 +456,8 @@ namespace ThingsGateway.SqlSugar public virtual ISugarQueryable Queryable( ISugarQueryable joinQueryable1, ISugarQueryable joinQueryable2, JoinType joinType, Expression> joinExpression) where T : class, new() where T2 : class, new() { - Check.Exception(joinQueryable1.QueryBuilder.Take != null || joinQueryable1.QueryBuilder.Skip != null || joinQueryable1.QueryBuilder.OrderByValue.HasValue(), "joinQueryable1 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); - Check.Exception(joinQueryable2.QueryBuilder.Take != null || joinQueryable2.QueryBuilder.Skip != null || joinQueryable2.QueryBuilder.OrderByValue.HasValue(), "joinQueryable2 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); + if (joinQueryable1.QueryBuilder.Take != null || joinQueryable1.QueryBuilder.Skip != null || joinQueryable1.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable1 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } + if (joinQueryable2.QueryBuilder.Take != null || joinQueryable2.QueryBuilder.Skip != null || joinQueryable2.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable2 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig); @@ -500,9 +500,9 @@ namespace ThingsGateway.SqlSugar JoinType joinType2, Expression> joinExpression2 ) where T : class, new() where T2 : class, new() where T3 : class, new() { - Check.Exception(joinQueryable1.QueryBuilder.Take != null || joinQueryable1.QueryBuilder.Skip != null || joinQueryable1.QueryBuilder.OrderByValue.HasValue(), "joinQueryable1 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); - Check.Exception(joinQueryable2.QueryBuilder.Take != null || joinQueryable2.QueryBuilder.Skip != null || joinQueryable2.QueryBuilder.OrderByValue.HasValue(), "joinQueryable2 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); - Check.Exception(joinQueryable3.QueryBuilder.Take != null || joinQueryable3.QueryBuilder.Skip != null || joinQueryable3.QueryBuilder.OrderByValue.HasValue(), "joinQueryable3 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); + if (joinQueryable1.QueryBuilder.Take != null || joinQueryable1.QueryBuilder.Skip != null || joinQueryable1.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable1 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } + if (joinQueryable2.QueryBuilder.Take != null || joinQueryable2.QueryBuilder.Skip != null || joinQueryable2.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable2 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } + if (joinQueryable3.QueryBuilder.Take != null || joinQueryable3.QueryBuilder.Skip != null || joinQueryable3.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable3 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig); @@ -554,10 +554,10 @@ namespace ThingsGateway.SqlSugar JoinType joinType3, Expression> joinExpression3 ) where T : class, new() where T2 : class, new() where T3 : class, new() where T4 : class, new() { - Check.Exception(joinQueryable1.QueryBuilder.Take != null || joinQueryable1.QueryBuilder.Skip != null || joinQueryable1.QueryBuilder.OrderByValue.HasValue(), "joinQueryable1 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); - Check.Exception(joinQueryable2.QueryBuilder.Take != null || joinQueryable2.QueryBuilder.Skip != null || joinQueryable2.QueryBuilder.OrderByValue.HasValue(), "joinQueryable2 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); - Check.Exception(joinQueryable3.QueryBuilder.Take != null || joinQueryable3.QueryBuilder.Skip != null || joinQueryable3.QueryBuilder.OrderByValue.HasValue(), "joinQueryable3 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); - Check.Exception(joinQueryable4.QueryBuilder.Take != null || joinQueryable4.QueryBuilder.Skip != null || joinQueryable4.QueryBuilder.OrderByValue.HasValue(), "joinQueryable4 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); + if (joinQueryable1.QueryBuilder.Take != null || joinQueryable1.QueryBuilder.Skip != null || joinQueryable1.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable1 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } + if (joinQueryable2.QueryBuilder.Take != null || joinQueryable2.QueryBuilder.Skip != null || joinQueryable2.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable2 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } + if (joinQueryable3.QueryBuilder.Take != null || joinQueryable3.QueryBuilder.Skip != null || joinQueryable3.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable3 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } + if (joinQueryable4.QueryBuilder.Take != null || joinQueryable4.QueryBuilder.Skip != null || joinQueryable4.QueryBuilder.OrderByValue.HasValue()) { throw new SqlSugarException("joinQueryable4 Cannot have 'Skip' 'ToPageList' 'Take' Or 'OrderBy'"); } var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig); sqlBuilder.Context = this; @@ -615,7 +615,7 @@ namespace ThingsGateway.SqlSugar internal ISugarQueryable _UnionAll(IReadOnlyCollection> queryables) { var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig); - Check.Exception(queryables.IsNullOrEmpty(), "UnionAll.queryables is null "); + if (queryables.IsNullOrEmpty()) { throw new SqlSugarException("UnionAll.queryables is null "); } int i = 1; var allItems = new List>>(); foreach (var item in queryables) @@ -656,14 +656,14 @@ namespace ThingsGateway.SqlSugar public virtual ISugarQueryable UnionAll(IReadOnlyCollection> queryables) where T : class { - Check.Exception(queryables.IsNullOrEmpty(), "UnionAll.queryables is null "); + if (queryables.IsNullOrEmpty()) { throw new SqlSugarException("UnionAll.queryables is null "); } return _UnionAll(queryables); } public virtual ISugarQueryable Union(IReadOnlyCollection> queryables) where T : class { var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig); - Check.Exception(queryables.IsNullOrEmpty(), "UnionAll.queryables is null "); + if (queryables.IsNullOrEmpty()) { throw new SqlSugarException("UnionAll.queryables is null "); } int i = 1; var allItems = new List>>(); foreach (var item in queryables) @@ -776,12 +776,12 @@ namespace ThingsGateway.SqlSugar } public virtual IInsertable InsertableT(T insertObj) where T : class, new() { - return this.Context.Insertable(new T[] { insertObj }); + return this.Context.Insertable([insertObj]); } public virtual IInsertable Insertable(Dictionary columnDictionary) where T : class, new() { InitMappingInfo(); - Check.Exception(columnDictionary == null || columnDictionary.Count == 0, "Insertable.columnDictionary can't be null"); + if (columnDictionary == null || columnDictionary.Count == 0) { throw new SqlSugarException("Insertable.columnDictionary can't be null"); } var insertObject = this.Context.Utilities.DeserializeObject(this.Context.Utilities.SerializeObject(columnDictionary)); var columns = columnDictionary.Select(it => it.Key).ToList(); return this.Context.InsertableT(insertObject).InsertColumns(columns); @@ -796,7 +796,7 @@ namespace ThingsGateway.SqlSugar else { var columns = (insertDynamicObject).GetType().GetProperties().Select(it => it.Name).ToList(); - Check.Exception(columns.IsNullOrEmpty(), "Insertable.updateDynamicObject can't be null"); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("Insertable.updateDynamicObject can't be null"); } T insertObject = this.Context.Utilities.DeserializeObject(this.Context.Utilities.SerializeObject(insertDynamicObject)); return this.Context.InsertableT(insertObject).InsertColumns(columns); } @@ -957,7 +957,7 @@ namespace ThingsGateway.SqlSugar public virtual IUpdateable Updateable(IReadOnlyCollection UpdateObjs) where T : class, new() { - //Check.ArgumentNullException(UpdateObjs, "Updateable.UpdateObjs can't be null"); + //if(UpdateObjs ==null){throw new SqlSugarException("Updateable.UpdateObjs can't be null");} if (UpdateObjs == null) { UpdateObjs = new List(); @@ -1004,7 +1004,7 @@ namespace ThingsGateway.SqlSugar public virtual IUpdateable Updateable(Dictionary columnDictionary) where T : class, new() { InitMappingInfo(); - Check.Exception(columnDictionary == null || columnDictionary.Count == 0, "Updateable.columnDictionary can't be null"); + if (columnDictionary == null || columnDictionary.Count == 0) { throw new SqlSugarException("Updateable.columnDictionary can't be null"); } var updateObject = this.Context.Utilities.DeserializeObject(this.Context.Utilities.SerializeObject(columnDictionary)); var columns = columnDictionary.Select(it => it.Key).ToList(); return this.Context.UpdateableT(updateObject).UpdateColumns(columns); @@ -1019,7 +1019,7 @@ namespace ThingsGateway.SqlSugar else { var columns = (updateDynamicObject).GetType().GetProperties().Select(it => it.Name).ToList(); - Check.Exception(columns.IsNullOrEmpty(), "Updateable.updateDynamicObject can't be null"); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("Updateable.updateDynamicObject can't be null"); } T updateObject = this.Context.Utilities.DeserializeObject(this.Context.Utilities.SerializeObject(updateDynamicObject)); return this.Context.UpdateableT(updateObject).UpdateColumns(columns); } @@ -1029,9 +1029,9 @@ namespace ThingsGateway.SqlSugar #region Saveable public GridSaveProvider GridSave(List saveList) where T : class, new() { - Check.ExceptionEasy(saveList == null, "saveList is null", "saveList 不能是 null"); + if (saveList == null) { throw new SqlSugarLangException("saveList is null", "saveList 不能是 null"); } var isTran = this.Context.TempItems?.Any(it => it.Key == "OldData_" + saveList.GetHashCode()) == true; - Check.ExceptionEasy(isTran == false, "saveList no tracking", "saveList 没有使用跟踪"); + if (isTran == false) { throw new SqlSugarLangException("saveList no tracking", "saveList 没有使用跟踪"); } var oldList = (List)this.Context.TempItems.FirstOrDefault(it => it.Key == "OldData_" + saveList.GetHashCode()).Value; return GridSave(oldList, saveList); } @@ -1082,7 +1082,7 @@ namespace ThingsGateway.SqlSugar public StorageableDataTable Storageable(DataTable data) { var result = new StorageableDataTable(); - Check.Exception(data.TableName.IsNullOrEmpty() || data.TableName == "Table", ErrorMessage.GetThrowMessage("DataTable data.TableName is null", "参数DataTable没有设置TableName ,参数.TableName=表名")); + if (data.TableName.IsNullOrEmpty() || data.TableName == "Table") { throw new SqlSugarException(ErrorMessage.GetThrowMessage("DataTable data.TableName is null", "参数DataTable没有设置TableName ,参数.TableName=表名")); } result.DataTable = data; result.Context = this; data.Columns.Add(new DataColumn("SugarGroupId", typeof(StorageType))); @@ -1327,12 +1327,12 @@ namespace ThingsGateway.SqlSugar #region SimpleClient public T CreateContext(bool isTran) where T : SugarUnitOfWork, new() { - Check.ExceptionEasy(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); + Check.ExceptionLang(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); return null; } public SugarUnitOfWork CreateContext(bool isTran = true) { - Check.ExceptionEasy(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); + Check.ExceptionLang(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); return null; } @@ -1727,8 +1727,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, ErrorMessage.GetThrowMessage("Child objects do not support tenant methods, var childDb= Db.GetConnection(confid) ,Db is master ", "Db子对象不支持租户方法,请使用主对象,例如:var childDb= Db.GetConnection(confid) Db是主对象,childDb是子对象 ")); - return null; + { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Child objects do not support tenant methods, var childDb= Db.GetConnection(confid) ,Db is master ", "Db子对象不支持租户方法,请使用主对象,例如:var childDb= Db.GetConnection(confid) Db是主对象,childDb是子对象 ")); } } } @@ -1784,7 +1783,7 @@ namespace ThingsGateway.SqlSugar } if (datas != null) { - Check.ExceptionEasy(this.Context.TempItems.ContainsKey("OldData_" + datas.GetHashCode()), "The object already has a trace", "对象已存在跟踪,如果要在跟踪可以先清除 db.ClearTracking() "); + if (this.Context.TempItems.ContainsKey("OldData_" + datas.GetHashCode())) { throw new SqlSugarLangException("The object already has a trace", "对象已存在跟踪,如果要在跟踪可以先清除 db.ClearTracking() "); } this.Context.TempItems.Add("OldData_" + datas.GetHashCode(), datas.Cast().ToList()); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs index 286a58d38..996637691 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/SugarProvider/SqlSugarScopeProvider.cs @@ -213,12 +213,12 @@ namespace ThingsGateway.SqlSugar } public T CreateContext(bool isTran) where T : SugarUnitOfWork, new() { - Check.ExceptionEasy(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); + Check.ExceptionLang(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); return null; } public SugarUnitOfWork CreateContext(bool isTran = true) { - Check.ExceptionEasy(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); + Check.ExceptionLang(" var childDb=Db.GetConnection(configId); use Db.CreateContext ", " 例如 var childDb=Db.GetConnection(configId);其中Db才能使用CreateContext,childDb不能使用"); return null; } public SimpleClient GetSimpleClient() where T : class, new() diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/ParameterUpdateable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/ParameterUpdateable.cs index f00f06539..e4122f8d2 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/ParameterUpdateable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/ParameterUpdateable.cs @@ -123,12 +123,12 @@ namespace ThingsGateway.SqlSugar StringBuilder sbAllSql = new StringBuilder(); var sqlTemp = ($" UPDATE {tableWithString} SET {{0}} WHERE {{1}};\r\n"); List parameters = new List(); - Check.ExceptionEasy(wheres?.Count == 0, "Updates cannot be without a primary key or condition", "更新不能没有主键或者条件"); + if (wheres?.Count == 0) { throw new SqlSugarLangException("Updates cannot be without a primary key or condition", "更新不能没有主键或者条件"); } var sqlDb = this.Context.CopyNew(); sqlDb.Aop.DataExecuting = null; foreach (var list in sqlDb.Updateable(updateObjects).UpdateBuilder.DbColumnInfoList.GroupBy(it => it.TableId)) { - Check.ExceptionEasy(list?.Any() != true, "Set has no columns", "更新Set没有列"); + if (list?.Any() != true) { throw new SqlSugarLangException("Set has no columns", "更新Set没有列"); } StringBuilder setString = new StringBuilder(); foreach (var setItem in list) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/SplitTableUpdateByObjectProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/SplitTableUpdateByObjectProvider.cs index ad7aee44f..fe1c729a6 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/SplitTableUpdateByObjectProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/SplitTableUpdateByObjectProvider.cs @@ -24,7 +24,7 @@ namespace ThingsGateway.SqlSugar var addList = item.Select(it => it.Item).ToList(); if (IsVersion()) { - //Check.ExceptionEasy(addList.Count > 1, "The version number can only be used for single record updates", "版本号只能用于单条记录更新"); + //if(addList.Count > 1){throw new SqlSugarLangException("The version number can only be used for single record updates", "版本号只能用于单条记录更新");} result += this.Context.UpdateableT(addList[0]) .WhereColumns(this.WhereColumns) .EnableDiffLogEventIF(this.IsEnableDiffLogEvent, this.BusinessData) @@ -97,7 +97,7 @@ namespace ThingsGateway.SqlSugar var addList = item.Select(it => it.Item).ToList(); if (IsVersion()) { - //Check.ExceptionEasy(addList.Count > 1, "The version number can only be used for single record updates", "版本号只能用于单条记录更新"); + //if(addList.Count > 1){throw new SqlSugarLangException("The version number can only be used for single record updates", "版本号只能用于单条记录更新");} result += await Context.UpdateableT(addList[0]) .WhereColumns(WhereColumns) .EnableDiffLogEventIF(IsEnableDiffLogEvent, BusinessData) @@ -134,7 +134,7 @@ namespace ThingsGateway.SqlSugar private IEnumerable GroupDataList(IEnumerable datas) { var attribute = typeof(T).GetCustomAttribute() as SplitTableAttribute; - Check.Exception(attribute == null, $"{typeof(T).Name} need SplitTableAttribute"); + if (attribute == null) { throw new SqlSugarException($"{typeof(T).Name} need SplitTableAttribute"); } var db = this.Context; var context = db.SplitHelper(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableHelper.cs index 85b4c2c45..6cf9b1457 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableHelper.cs @@ -144,8 +144,8 @@ namespace ThingsGateway.SqlSugar CheckWhere(); PreToSql(); AutoRemoveDataCache(); - Check.ExceptionEasy(this.UpdateParameterIsNull && this.UpdateBuilder.DbColumnInfoList.Count == this.UpdateObjs.Count && this.UpdateObjs.Count == this.UpdateBuilder.DbColumnInfoList.Count(it => it.IsPrimarykey), "The primary key cannot be updated", "主键不能更新,更新主键会对代码逻辑存在未知隐患,如果非要更新:建议你删除在插入或者新建一个没主键的类。"); - Check.Exception(UpdateBuilder.WhereValues.IsNullOrEmpty() && GetPrimaryKeys().IsNullOrEmpty(), "You cannot have no primary key and no conditions"); + if (this.UpdateParameterIsNull && this.UpdateBuilder.DbColumnInfoList.Count == this.UpdateObjs.Count && this.UpdateObjs.Count == this.UpdateBuilder.DbColumnInfoList.Count(it => it.IsPrimarykey)) { throw new SqlSugarLangException("The primary key cannot be updated", "主键不能更新,更新主键会对代码逻辑存在未知隐患,如果非要更新:建议你删除在插入或者新建一个没主键的类。"); } + if (UpdateBuilder.WhereValues.IsNullOrEmpty() && GetPrimaryKeys().IsNullOrEmpty()) { throw new SqlSugarException("You cannot have no primary key and no conditions"); } string sql = UpdateBuilder.ToSqlString(); ValidateVersion(); RestoreMapping(); @@ -157,7 +157,7 @@ namespace ThingsGateway.SqlSugar { if (UpdateParameterIsNull && UpdateBuilder.WhereValues.IsNullOrEmpty()) { - Check.ExceptionEasy("Update requires conditions", "更新需要条件 Where"); + Check.ExceptionLang("Update requires conditions", "更新需要条件 Where"); } } @@ -190,7 +190,7 @@ namespace ThingsGateway.SqlSugar this.UpdateBuilder.TableName = mappingInfo.DbTableName; } } - //Check.Exception(UpdateObjs == null || UpdateObjs.Any(), "UpdateObjs is null"); + //if(UpdateObjs == null || UpdateObjs.Any()){throw new SqlSugarException("UpdateObjs is null");} int i = 0; if (this.EntityInfo.Columns.Any(it => it.IsPrimarykey)) { @@ -202,7 +202,7 @@ namespace ThingsGateway.SqlSugar var isDic = item is Dictionary; if (item is Dictionary) { - Check.ExceptionEasy("To use Updateable dictionary, use string or object", "Updateable字典请使用string,object类型"); + Check.ExceptionLang("To use Updateable dictionary, use string or object", "Updateable字典请使用string,object类型"); } if (isDic) { @@ -334,15 +334,15 @@ namespace ThingsGateway.SqlSugar { if (this.EntityInfo.Columns.Any(it => it.IsTranscoding)) { - Check.Exception(true, ErrorMessage.GetThrowMessage("UpdateColumns no support IsTranscoding", "SetColumns方式更新不支持IsTranscoding,你可以使用db.Updateable(实体)的方式更新")); + { throw new SqlSugarException(ErrorMessage.GetThrowMessage("UpdateColumns no support IsTranscoding", "SetColumns方式更新不支持IsTranscoding,你可以使用db.Updateable(实体)的方式更新")); } } //if (checkIsJson && this.EntityInfo.Columns.Any(it => it.IsJson)) //{ - // Check.Exception(true, ErrorMessage.GetThrowMessage("UpdateColumns no support IsJson", "SetColumns方式更新不支持IsJson,你可以使用db.Updateable(实体)的方式更新")); + // {throw new SqlSugarException(ErrorMessage.GetThrowMessage("UpdateColumns no support IsJson", "SetColumns方式更新不支持IsJson,你可以使用db.Updateable(实体)的方式更新"));} //} //if (this.EntityInfo.Columns.Any(it => it.IsArray)) //{ - // Check.Exception(true, ErrorMessage.GetThrowMessage("UpdateColumns no support IsArray", "SetColumns方式更新不支持IsArray,你可以使用db.Updateable(实体)的方式更新")); + // {throw new SqlSugarException(ErrorMessage.GetThrowMessage("UpdateColumns no support IsArray", "SetColumns方式更新不支持IsArray,你可以使用db.Updateable(实体)的方式更新"));} //} } private void SetUpdateItemByDic(int i, T item, List updateItem) @@ -378,7 +378,7 @@ namespace ThingsGateway.SqlSugar foreach (var column in EntityInfo.Columns) { if (column.IsIgnore) continue; - Check.ExceptionEasy(item == null, "db.Updateable(data) data is required ", "db.Updateable(data) data不能是null"); + if (item == null) { throw new SqlSugarLangException("db.Updateable(data) data is required ", "db.Updateable(data) data不能是null"); } var columnInfo = new DbColumnInfo() { Value = GetValue(item, column), @@ -484,7 +484,7 @@ namespace ThingsGateway.SqlSugar continue; } var isContains = this.UpdateBuilder.DbColumnInfoList.Select(it => it.DbColumnName).Contains(pkName, StringComparer.OrdinalIgnoreCase); - Check.Exception(isContains == false, "Use UpdateColumns().WhereColumn() ,UpdateColumns need {0}", pkName); + if (isContains == false) { throw new SqlSugarException("Use UpdateColumns().WhereColumn() ,UpdateColumns need {0}", pkName); } } } #region IgnoreColumns @@ -649,7 +649,7 @@ namespace ThingsGateway.SqlSugar var pks = this.UpdateBuilder.DbColumnInfoList.Where(it => it.IsPrimarykey); if (versionColumn != null && this.IsVersionValidation) { - Check.Exception(pks.IsNullOrEmpty(), "UpdateVersionValidation the primary key is required."); + if (pks.IsNullOrEmpty()) { throw new SqlSugarException("UpdateVersionValidation the primary key is required."); } List conModels = new List(); foreach (var item in pks) { @@ -660,8 +660,8 @@ namespace ThingsGateway.SqlSugar { var currentVersion = this.EntityInfo.Type.GetProperty(versionColumn.PropertyName).GetValue(UpdateObjs.Last(), null); var dbVersion = this.EntityInfo.Type.GetProperty(versionColumn.PropertyName).GetValue(dbInfo, null); - Check.Exception(currentVersion == null, "UpdateVersionValidation entity property {0} is not null", versionColumn.PropertyName); - Check.Exception(dbVersion == null, "UpdateVersionValidation database column {0} is not null", versionColumn.DbColumnName); + if (currentVersion == null) { throw new SqlSugarException("UpdateVersionValidation entity property {0} is not null", versionColumn.PropertyName); } + if (dbVersion == null) { throw new SqlSugarException("UpdateVersionValidation database column {0} is not null", versionColumn.DbColumnName); } if (versionColumn.PropertyInfo.PropertyType.IsIn(UtilConstants.IntType, UtilConstants.LongType)) { if (Convert.ToInt64(dbVersion) != Convert.ToInt64(currentVersion)) @@ -714,11 +714,11 @@ namespace ThingsGateway.SqlSugar } private string _ExecuteCommandWithOptLock(T updateData, ref object oldVerValue) { - Check.ExceptionEasy(UpdateParameterIsNull == true, "Optimistic lock can only be an entity update method", "乐观锁只能是实体更新方式"); + if (UpdateParameterIsNull == true) { throw new SqlSugarLangException("Optimistic lock can only be an entity update method", "乐观锁只能是实体更新方式"); } var verColumn = this.EntityInfo.Columns.FirstOrDefault(it => it.IsEnableUpdateVersionValidation); - Check.ExceptionEasy(verColumn == null, $" {this.EntityInfo.EntityName} need IsEnableUpdateVersionValidation=true ", $"实体{this.EntityInfo.EntityName}没有找到版本标识特性 IsEnableUpdateVersionValidation"); - Check.ExceptionEasy(UpdateObjs.Count > 1, $"Optimistic lock can only handle a single update ", $"乐观锁只能处理单条更新"); - Check.ExceptionEasy(!verColumn.UnderType.IsIn(UtilConstants.StringType, UtilConstants.LongType, UtilConstants.GuidType, UtilConstants.DateType), $"Optimistic locks can only be guid, long, and string types", $"乐观锁只能是Guid、Long和字符串类型"); + if (verColumn == null) { throw new SqlSugarLangException($" {this.EntityInfo.EntityName} need IsEnableUpdateVersionValidation=true ", $"实体{this.EntityInfo.EntityName}没有找到版本标识特性 IsEnableUpdateVersionValidation"); } + if (UpdateObjs.Count > 1) { throw new SqlSugarLangException($"Optimistic lock can only handle a single update ", $"乐观锁只能处理单条更新"); } + if (!verColumn.UnderType.IsIn(UtilConstants.StringType, UtilConstants.LongType, UtilConstants.GuidType, UtilConstants.DateType)) { throw new SqlSugarLangException($"Optimistic locks can only be guid, long, and string types", $"乐观锁只能是Guid、Long和字符串类型"); } var oldValue = verColumn.PropertyInfo.GetValue(updateData); oldVerValue = oldValue; var newValue = UtilMethods.GetRandomByType(verColumn.UnderType); @@ -732,7 +732,7 @@ namespace ThingsGateway.SqlSugar } data.Value = newValue; var pks = GetPrimaryKeys(); - Check.ExceptionEasy(pks?.Any() != true, "need primary key or WhereColumn", "需要主键或者WhereColumn"); + if (pks?.Any() != true) { throw new SqlSugarLangException("need primary key or WhereColumn", "需要主键或者WhereColumn"); } this.Where(verColumn.DbColumnName, "=", oldValue); foreach (var p in pks) { @@ -789,7 +789,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.ExceptionEasy(col.ColumnName + " No corresponding entity attribute found in difference log ." + ex.Message, col.ColumnName + "在差异日志中可能没有找到相应的实体属性,详细:" + ex.Message); + Check.ExceptionLang(col.ColumnName + " No corresponding entity attribute found in difference log ." + ex.Message, col.ColumnName + "在差异日志中可能没有找到相应的实体属性,详细:" + ex.Message); } } result.Add(item); @@ -862,7 +862,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.ExceptionEasy(col.ColumnName + " No corresponding entity attribute found in difference log ." + ex.Message, col.ColumnName + "在差异日志中可能没有找到相应的实体属性,详细:" + ex.Message); + Check.ExceptionLang(col.ColumnName + " No corresponding entity attribute found in difference log ." + ex.Message, col.ColumnName + "在差异日志中可能没有找到相应的实体属性,详细:" + ex.Message); } } result.Add(item); @@ -882,19 +882,19 @@ namespace ThingsGateway.SqlSugar protected void ThrowUpdateByExpression() { - Check.Exception(UpdateParameterIsNull == true, ErrorMessage.GetThrowMessage(" no support UpdateColumns and WhereColumns", "根据表达式更新 db.Updateable() 禁止使用 UpdateColumns和WhereColumns,你可以使用 SetColumns Where 等。更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新, 具体用法请查看文档 ")); + if (UpdateParameterIsNull == true) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(" no support UpdateColumns and WhereColumns", "根据表达式更新 db.Updateable() 禁止使用 UpdateColumns和WhereColumns,你可以使用 SetColumns Where 等。更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新, 具体用法请查看文档 ")); } } protected void ThrowUpdateByObject() { - Check.Exception(UpdateParameterIsNull == false, ErrorMessage.GetThrowMessage(" no support SetColumns and Where", "根据对像更新 db.Updateabe(对象) 禁止使用 SetColumns和Where ,你可以使用WhereColumns 和 UpdateColumns。 更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新 , 具体用法请查看文档 ")); + if (UpdateParameterIsNull == false) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(" no support SetColumns and Where", "根据对像更新 db.Updateabe(对象) 禁止使用 SetColumns和Where ,你可以使用WhereColumns 和 UpdateColumns。 更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新 , 具体用法请查看文档 ")); } } protected void ThrowUpdateByExpressionByMesage(string message) { - Check.Exception(UpdateParameterIsNull == true, ErrorMessage.GetThrowMessage(" no support " + message, "根据表达式更新 db.Updateable()禁止使用 " + message + "。 更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新 , 具体用法请查看文档 ")); + if (UpdateParameterIsNull == true) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(" no support " + message, "根据表达式更新 db.Updateable()禁止使用 " + message + "。 更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新 , 具体用法请查看文档 ")); } } private void ThrowUpdateByObjectByMesage(string message) { - Check.Exception(UpdateParameterIsNull == false, ErrorMessage.GetThrowMessage(" no support " + message, "根据对象更新 db.Updateable(对象)禁止使用 " + message + "。 更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新 , 具体用法请查看文档 ")); + if (UpdateParameterIsNull == false) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(" no support " + message, "根据对象更新 db.Updateable(对象)禁止使用 " + message + "。 更新分为2种方式 1.根据表达式更新 2.根据实体或者集合更新 , 具体用法请查看文档 ")); } } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableProvider.cs index 3cdde2007..38804aadf 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Abstract/UpdateProvider/UpdateableProvider.cs @@ -71,7 +71,7 @@ namespace ThingsGateway.SqlSugar } public virtual int ExecuteCommandWithOptLock(bool IsVersionValidation = false) { - Check.ExceptionEasy(UpdateObjs?.Count > 1, " OptLock can only be used on a single object, and the argument cannot be List", "乐观锁只能用于单个对象,参数不能是List,如果是一对多操作请更新主表统一用主表验证"); + if (UpdateObjs?.Count > 1) { throw new SqlSugarLangException(" OptLock can only be used on a single object, and the argument cannot be List", "乐观锁只能用于单个对象,参数不能是List,如果是一对多操作请更新主表统一用主表验证"); } var updateData = UpdateObjs.First(); if (updateData == null) return 0; object oldValue = null; @@ -159,7 +159,7 @@ namespace ThingsGateway.SqlSugar public virtual async Task ExecuteCommandWithOptLockAsync(bool IsVersionValidation = false) { - Check.ExceptionEasy(UpdateObjs?.Count > 1, " OptLock can only be used on a single object, and the argument cannot be List", "乐观锁只能用于单个对象,参数不能是List,如果是一对多操作请更新主表统一用主表验证"); + if (UpdateObjs?.Count > 1) { throw new SqlSugarLangException(" OptLock can only be used on a single object, and the argument cannot be List", "乐观锁只能用于单个对象,参数不能是List,如果是一对多操作请更新主表统一用主表验证"); } var updateData = UpdateObjs.First(); if (updateData == null) return 0; object oldValue = null; @@ -344,7 +344,7 @@ namespace ThingsGateway.SqlSugar public SplitTableUpdateByObjectProvider SplitTable() { UtilMethods.StartCustomSplitTable(this.Context, typeof(T)); - Check.ExceptionEasy(UpdateParameterIsNull, "SplitTable() not supported db.Updateable(),use db.Updateable(list)", ".SplitTable()不支持 db.Updateable()方式更新,请使用 db.Updateable(list) 对象方式更新, 或者使用 .SplitTable(+1)重载"); + if (UpdateParameterIsNull) { throw new SqlSugarLangException("SplitTable() not supported db.Updateable(),use db.Updateable(list)", ".SplitTable()不支持 db.Updateable()方式更新,请使用 db.Updateable(list) 对象方式更新, 或者使用 .SplitTable(+1)重载"); } SplitTableUpdateByObjectProvider result = new SplitTableUpdateByObjectProvider(); result.Context = this.Context; result.UpdateObjects = this.UpdateObjs; @@ -413,7 +413,7 @@ namespace ThingsGateway.SqlSugar } public IUpdateable EnableDiffLogEvent(object businessData = null) { - //Check.Exception(this.UpdateObjs.HasValue() && this.UpdateObjs.Count() > 1, "DiffLog does not support batch operations"); + //if(this.UpdateObjs.HasValue() && this.UpdateObjs.Count() > 1){throw new SqlSugarException("DiffLog does not support batch operations");} DiffModel = new DiffLogModel(); this.IsEnableDiffLogEvent = true; DiffModel.BusinessData = businessData; @@ -423,7 +423,7 @@ namespace ThingsGateway.SqlSugar public IUpdateable IgnoreColumns(bool ignoreAllNullColumns, bool isOffIdentity = false, bool ignoreAllDefaultValue = false) { - //Check.Exception(this.UpdateObjs.Count() > 1 && ignoreAllNullColumns, ErrorMessage.GetThrowMessage("ignoreNullColumn NoSupport batch insert", "ignoreNullColumn 不支持批量操作")); + //if(this.UpdateObjs.Count() > 1 && ignoreAllNullColumns){throw new SqlSugarException(ErrorMessage.GetThrowMessage("ignoreNullColumn NoSupport batch insert", "ignoreNullColumn 不支持批量操作"));} UpdateBuilder.IsOffIdentity = isOffIdentity; if (this.UpdateBuilder.LambdaExpressions == null) this.UpdateBuilder.LambdaExpressions = InstanceFactory.GetLambdaExpressions(this.Context.CurrentConnectionConfig); @@ -489,14 +489,14 @@ namespace ThingsGateway.SqlSugar { if (UpdateParameterIsNull == true) { - Check.Exception(UpdateParameterIsNull == true, ErrorMessage.GetThrowMessage("The PublicSetColumns(exp,string) overload can only be used to update entity objects: db.Updateable(object)", "PublicSetColumns(exp,string)重载只能用在实体对象更新:db.Updateable(对象),请区分表达式更新和实体对象更不同用法 ")); + if (UpdateParameterIsNull == true) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("The PublicSetColumns(exp,string) overload can only be used to update entity objects: db.Updateable(object)", "PublicSetColumns(exp,string)重载只能用在实体对象更新:db.Updateable(对象),请区分表达式更新和实体对象更不同用法 ")); } } else { var name = ExpressionTool.GetMemberName(fieldNameExpression); if (name == null) { - Check.ExceptionEasy(fieldNameExpression + " format error ", fieldNameExpression + "参数格式错误"); + Check.ExceptionLang(fieldNameExpression + " format error ", fieldNameExpression + "参数格式错误"); } //var value = this.UpdateBuilder.GetExpressionValue(ValueExpExpression, ResolveExpressType.WhereSingle).GetResultString(); if (this.UpdateBuilder.ReSetValueBySqlExpList == null) @@ -527,7 +527,7 @@ namespace ThingsGateway.SqlSugar var name = ExpressionTool.GetMemberName(fieldNameExpression); if (name == null) { - Check.ExceptionEasy(fieldNameExpression + " format error ", fieldNameExpression + "参数格式错误"); + Check.ExceptionLang(fieldNameExpression + " format error ", fieldNameExpression + "参数格式错误"); } var value = this.UpdateBuilder.GetExpressionValue(ValueExpExpression, ResolveExpressType.WhereSingle).GetResultString(); if (this.UpdateBuilder.ReSetValueBySqlExpList == null) @@ -555,7 +555,7 @@ namespace ThingsGateway.SqlSugar { var oldColumns = this.UpdateBuilder.DbColumnInfoList.Select(it => it.PropertyName).ToHashSet(); var expression = (LambdaExpression.Lambda(method).Body as LambdaExpression).Body; - Check.Exception(!(expression is MethodCallExpression), method.ToString() + " is not method"); + if (!(expression is MethodCallExpression)) { throw new SqlSugarException(method.ToString() + " is not method"); } var callExpresion = expression as MethodCallExpression; UtilMethods.DataInoveByExpresson(this.UpdateObjs, callExpresion); this.UpdateBuilder.DbColumnInfoList = new List(); @@ -570,7 +570,7 @@ namespace ThingsGateway.SqlSugar ThrowUpdateByExpression(); this.IsWhereColumns = true; UpdateBuilder.IsWhereColumns = true; - Check.Exception(UpdateParameterIsNull == true, "Updateable().Updateable is error,Use Updateable(obj).WhereColumns"); + if (UpdateParameterIsNull == true) { throw new SqlSugarException("Updateable().Updateable is error,Use Updateable(obj).WhereColumns"); } var whereColumns = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.ArraySingle).GetResultArray().Select(it => this.SqlBuilder.GetNoTranslationColumnName(it)); if (this.WhereColumnList == null) this.WhereColumnList = new List(); foreach (var item in whereColumns) @@ -691,7 +691,7 @@ namespace ThingsGateway.SqlSugar } catch { - Check.ExceptionEasy("Updateable(obj) no support, use Updateable().SetColumn ", "更新过滤器只能用在表达式方式更新 ,更新分为实体更新和表达式更新 。正确用法 Updateable().SetColum(..).Where(..)"); + Check.ExceptionLang("Updateable(obj) no support, use Updateable().SetColumn ", "更新过滤器只能用在表达式方式更新 ,更新分为实体更新和表达式更新 。正确用法 Updateable().SetColum(..).Where(..)"); } var queryable = this.Context.Queryable(); queryable.QueryBuilder.LambdaExpressions.ParameterIndex = 1000; @@ -813,7 +813,7 @@ namespace ThingsGateway.SqlSugar ThrowUpdateByObject(); var expResult = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.Update); var resultArray = expResult.GetResultArray(); - Check.ArgumentNullException(resultArray, "UpdateColumns Parameter error, UpdateColumns(it=>new T{ it.id=1}) is valid, UpdateColumns(it=>T) is error"); + if (resultArray == null) { throw new SqlSugarException("UpdateColumns Parameter error, UpdateColumns(it=>new T{ it.id=1}) is valid, UpdateColumns(it=>T) is error"); } var keys = ExpressionTool.GetNewExpressionItemList(columns).ToArray(); if (resultArray.HasValue()) { @@ -839,7 +839,7 @@ namespace ThingsGateway.SqlSugar ThrowUpdateByObject(); var expResult = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.Update); var resultArray = expResult.GetResultArray(); - Check.ArgumentNullException(resultArray, "UpdateColumns Parameter error, UpdateColumns(it=>new T{ it.id=1}) is valid, UpdateColumns(it=>T) is error"); + if (resultArray == null) { throw new SqlSugarException("UpdateColumns Parameter error, UpdateColumns(it=>new T{ it.id=1}) is valid, UpdateColumns(it=>T) is error"); } if (resultArray.HasValue()) { foreach (var item in resultArray) @@ -899,9 +899,9 @@ namespace ThingsGateway.SqlSugar ThrowUpdateByObject(); var binaryExp = columns.Body as BinaryExpression; - Check.Exception(!binaryExp.NodeType.IsIn(ExpressionType.Equal), "No support {0}", columns.ToString()); - Check.Exception(!(binaryExp.Left is MemberExpression) && !(binaryExp.Left is UnaryExpression), "No support {0}", columns.ToString()); - Check.Exception(ExpressionTool.IsConstExpression(binaryExp.Left as MemberExpression), "No support {0}", columns.ToString()); + if (!binaryExp.NodeType.IsIn(ExpressionType.Equal)) { throw new SqlSugarException("No support {0}", columns.ToString()); } + if (!(binaryExp.Left is MemberExpression) && !(binaryExp.Left is UnaryExpression)) { throw new SqlSugarException("No support {0}", columns.ToString()); } + if (ExpressionTool.IsConstExpression(binaryExp.Left as MemberExpression)) { throw new SqlSugarException("No support {0}", columns.ToString()); } if (UpdateBuilder.LambdaExpressions.ParameterIndex <= 1 && this.EntityInfo.Columns .Select(it => it.PropertyName.TrimEnd('2')) @@ -983,7 +983,7 @@ namespace ThingsGateway.SqlSugar { if (UpdateBuilder.WhereValues.Count != 0 != true) { - Check.ExceptionEasy(!StaticConfig.EnableAllWhereIF, "Need to program startup configuration StaticConfig. EnableAllWhereIF = true; Tip: This operation is very risky if there are no conditions it is easy to update the entire table", " 需要程序启动时配置StaticConfig.EnableAllWhereIF=true; 提示:该操作存在很大的风险如果没有条件很容易将整个表全部更新"); + if (!StaticConfig.EnableAllWhereIF) { throw new SqlSugarLangException("Need to program startup configuration StaticConfig. EnableAllWhereIF = true; Tip: This operation is very risky if there are no conditions it is easy to update the entire table", " 需要程序启动时配置StaticConfig.EnableAllWhereIF=true; 提示:该操作存在很大的风险如果没有条件很容易将整个表全部更新"); } } if (isWhere) { @@ -993,7 +993,7 @@ namespace ThingsGateway.SqlSugar } public IUpdateable Where(Expression> expression) { - Check.Exception(UpdateObjectNotWhere() && UpdateObjs.Count > 1, ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); + if (UpdateObjectNotWhere() && UpdateObjs.Count > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); } var expResult = UpdateBuilder.GetExpressionValue(expression, ResolveExpressType.WhereSingle); var whereString = expResult.GetResultString(); if (expression.ToString().Contains("Subqueryable()")) @@ -1025,7 +1025,7 @@ namespace ThingsGateway.SqlSugar } public IUpdateable Where(string whereSql, object parameters = null) { - Check.Exception(UpdateObjectNotWhere() && UpdateObjs.Count > 1, ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); + if (UpdateObjectNotWhere() && UpdateObjs.Count > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); } if (whereSql.HasValue()) { UpdateBuilder.WhereValues.Add(whereSql); @@ -1038,7 +1038,7 @@ namespace ThingsGateway.SqlSugar } public IUpdateable Where(string fieldName, string conditionalType, object fieldValue) { - Check.Exception(UpdateObjectNotWhere() && UpdateObjs.Count > 1, ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); + if (UpdateObjectNotWhere() && UpdateObjs.Count > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); } var whereSql = this.SqlBuilder.GetWhere(fieldName, conditionalType, 0); this.Where(whereSql); string parameterName = this.SqlBuilder.SqlParameterKeyWord + fieldName + "0"; @@ -1047,7 +1047,7 @@ namespace ThingsGateway.SqlSugar } public IUpdateable Where(List conditionalModels) { - Check.Exception(UpdateObjectNotWhere() && UpdateObjs.Count > 1, ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); + if (UpdateObjectNotWhere() && UpdateObjs.Count > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns")); } var sql = this.Context.Queryable().SqlBuilder.ConditionalModelToSql(conditionalModels); var result = this; result.Where(sql.Key, sql.Value); @@ -1066,7 +1066,7 @@ namespace ThingsGateway.SqlSugar ThrowUpdateByObjectByMesage(" In(object[] ids) "); List conditionalModels = new List(); var column = this.EntityInfo.Columns.FirstOrDefault(it => it.IsPrimarykey); - Check.ExceptionEasy(column == null, "In need primary key", "In需要实体有主键"); + if (column == null) { throw new SqlSugarLangException("In need primary key", "In需要实体有主键"); } conditionalModels.Add(new ConditionalModel() { FieldName = column.DbColumnName, ConditionalType = ConditionalType.In, FieldValue = string.Join(",", ids), CSharpTypeName = column.UnderType?.Name }); return this.Where(conditionalModels); } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ConfigQuery.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ConfigQuery.cs index a5cb72dbb..7b21c61a5 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ConfigQuery.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ConfigQuery.cs @@ -34,7 +34,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, "SetKeyValue error , entity & uniqueCode already exist"); + { throw new SqlSugarException("SetKeyValue error , entity & uniqueCode already exist"); } } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/DbFastestProperties.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/DbFastestProperties.cs index 15b638ff0..553ee2303 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/DbFastestProperties.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/DbFastestProperties.cs @@ -7,6 +7,7 @@ public bool IsOffIdentity { get; set; } public bool IsMerge { get; set; } public bool IsNoCopyDataTable { get; set; } + public bool IsDataTable { get; set; } = true; public bool IsConvertDateTimeOffsetToDateTime { get; set; } public bool NoPage { get; set; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/Mapping/SugarMappingAttribute.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/Mapping/SugarMappingAttribute.cs index deef7719e..0f3dbfb6a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/Mapping/SugarMappingAttribute.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/Mapping/SugarMappingAttribute.cs @@ -273,7 +273,7 @@ } public Navigate(NavigateType navigatType, string ifSingleMasterTableColumn_IfListChildTableColumn, string ifSingleChildTableColumn_IfListMasterTableColumn) { - Check.ExceptionEasy(navigatType == NavigateType.ManyToMany, "Correct usage [Navigate(typeof(ABMapping), nameof(abmapping.aid), nameof(abmapp.bid))], incorrect usage: [Navigate(Navigate.ManyToMany, nameof(ABMapping.Aid), nameof(ABMapping.BId))]", "多对多第一个参数是Type不是NavigateType,正确用法[Navigate(typeof(ABMapping), nameof(ABMapping.Aid), nameof(ABMapping.BId))],错误用法:[Navigate(Navigate.ManyToMany, nameof(ABMapping.Aid), nameof(ABMapping.BId))]"); + if (navigatType == NavigateType.ManyToMany) { throw new SqlSugarLangException("Correct usage [Navigate(typeof(ABMapping), nameof(abmapping.aid), nameof(abmapp.bid))], incorrect usage: [Navigate(Navigate.ManyToMany, nameof(ABMapping.Aid), nameof(ABMapping.BId))]", "多对多第一个参数是Type不是NavigateType,正确用法[Navigate(typeof(ABMapping), nameof(ABMapping.Aid), nameof(ABMapping.BId))],错误用法:[Navigate(Navigate.ManyToMany, nameof(ABMapping.Aid), nameof(ABMapping.BId))]"); } this.Name = ifSingleMasterTableColumn_IfListChildTableColumn; this.Name2 = ifSingleChildTableColumn_IfListMasterTableColumn; this.NavigatType = navigatType; @@ -285,7 +285,7 @@ this.Name2 = ifSingleChildTableColumn_IfListMasterTableColumn; this.NavigatType = navigatType; this.WhereSql = whereSql; - //Check.ExceptionEasy(navigatType != NavigateType.OneToOne, "Currently, only one-to-one navigation configuration Sql conditions are supported", "目前导航配置Sql条件只支持一对一"); + //if(navigatType != NavigateType.OneToOne){throw new SqlSugarLangException("Currently, only one-to-one navigation configuration Sql conditions are supported", "目前导航配置Sql条件只支持一对一");} } public Navigate(Type MappingTableType, string typeAId, string typeBId) @@ -440,7 +440,7 @@ { if (fieldNames.Length != sortTypes.Length) { - Check.ExceptionEasy($"SugarIndexAttribute {indexName} fieldNames.Length!=sortTypes.Length 检查索引特性", $"SugarIndexAttribute {indexName} fieldNames.Length!=sortTypes.Length"); + Check.ExceptionLang($"SugarIndexAttribute {indexName} fieldNames.Length!=sortTypes.Length 检查索引特性", $"SugarIndexAttribute {indexName} fieldNames.Length!=sortTypes.Length"); } this.IndexName = indexName; IndexFields = new Dictionary(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ModelContext.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ModelContext.cs index ddecf6911..ca90ed6dc 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ModelContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Entities/ModelContext.cs @@ -9,7 +9,7 @@ namespace ThingsGateway.SqlSugar public SqlSugarProvider Context { get; set; } public ISugarQueryable CreateMapping() where T : class, new() { - Check.ArgumentNullException(Context, "Please use Sqlugar.ModelContext"); + if (Context == null) { throw new SqlSugarException("Please use Sqlugar.ModelContext"); } using (Context) { return Context.Queryable(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Enum/DataFilterType.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Enum/DataFilterType.cs index d33af2a38..124ae521a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Enum/DataFilterType.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Enum/DataFilterType.cs @@ -29,7 +29,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.ExceptionEasy($" SetValue error in DataExecuting {EntityName} . {ex.Message}", $" DataExecuting 中 SetValue出错 {EntityName} 。 {ex.Message}"); + Check.ExceptionLang($" SetValue error in DataExecuting {EntityName} . {ex.Message}", $" DataExecuting 中 SetValue出错 {EntityName} 。 {ex.Message}"); } } public bool IsAnyAttribute() where T : Attribute @@ -49,13 +49,13 @@ namespace ThingsGateway.SqlSugar public object GetValue(string propertyName) { var property = EntityColumnInfos.FirstOrDefault(it => it.PropertyName == propertyName); - Check.ExceptionEasy(property == null, $"Aop.DataExecuted error . {Entity.EntityName} no property {propertyName}.", $"Aop.DataExecuted 出错 {Entity.EntityName}不存在属性{propertyName}"); + if (property == null) { throw new SqlSugarLangException($"Aop.DataExecuted error . {Entity.EntityName} no property {propertyName}.", $"Aop.DataExecuted 出错 {Entity.EntityName}不存在属性{propertyName}"); } return property.PropertyInfo.GetValue(EntityValue); } public void SetValue(string propertyName, object value) { var property = EntityColumnInfos.FirstOrDefault(it => it.PropertyName == propertyName); - Check.ExceptionEasy(property == null, $"Aop.DataExecuted error . {Entity.EntityName} no property {propertyName}.", $"Aop.DataExecuted 出错 {Entity.EntityName}不存在属性{propertyName}"); + if (property == null) { throw new SqlSugarLangException($"Aop.DataExecuted error . {Entity.EntityName} no property {propertyName}.", $"Aop.DataExecuted 出错 {Entity.EntityName}不存在属性{propertyName}"); } property.PropertyInfo.SetValue(EntityValue, value); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ErrorMessage.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ErrorMessage.cs index f898d50c2..dc11e68d7 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ErrorMessage.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ErrorMessage.cs @@ -25,13 +25,7 @@ } } - public static string ConnnectionOpen - { - get - { - return ErrorMessage.GetThrowMessage("Connection open error . {0} ", " 连接数据库过程中发生错误,检查服务器是否正常连接字符串是否正确,错误信息:{0}."); - } - } + public const string ConnnectionOpen = "Connection open error . "; public static string ExpressionCheck { get diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionResult.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionResult.cs index 44438e641..f64340238 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionResult.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionResult.cs @@ -15,7 +15,7 @@ namespace ThingsGateway.SqlSugar } set { - Check.Exception(value != null && IsLockCurrentParameter, "CurrentParameter is locked."); + if (value != null && IsLockCurrentParameter) { throw new SqlSugarException("CurrentParameter is locked."); } this._CurrentParameter = value; this.IsLockCurrentParameter = false; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionTool.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionTool.cs index 8de966921..29504a746 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionTool.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/ExpressionTool.cs @@ -307,7 +307,7 @@ namespace ThingsGateway.SqlSugar var exp = caseExp as NewExpression; if (exp == null) { - Check.ExceptionEasy("Use Select(it=>new class(){})", "导航查询请使用Select(it=>new class(){})"); + Check.ExceptionLang("Use Select(it=>new class(){})", "导航查询请使用Select(it=>new class(){})"); } var dict = new Dictionary(); @@ -419,15 +419,15 @@ namespace ThingsGateway.SqlSugar var navObjectName2 = navObjectName; var navObjectNameProperty = listItemType.GetProperty(navObjectName); var navObjectNameColumnInfo = listItemEntity.Columns.First(it => it.PropertyName == navObjectName2); - Check.ExceptionEasy(navObjectNameColumnInfo.Navigat == null, $"{navObjectName} not [Navigat(..)] ", $"{navObjectName} 没有导航特性 [Navigat(..)] "); - Check.ExceptionEasy(navObjectNameColumnInfo.Navigat.NavigatType != NavigateType.OneToOne, $"IncludeLeftJoin can only be one-on-one ", $"IncludeLeftJoin 只能是一对一 "); + if (navObjectNameColumnInfo.Navigat == null) { throw new SqlSugarLangException($"{navObjectName} not [Navigat(..)] ", $"{navObjectName} 没有导航特性 [Navigat(..)] "); } + if (navObjectNameColumnInfo.Navigat.NavigatType != NavigateType.OneToOne) { throw new SqlSugarLangException($"IncludeLeftJoin can only be one-on-one ", $"IncludeLeftJoin 只能是一对一 "); } navColumn = listItemEntity.Columns.FirstOrDefault(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name); - Check.ExceptionEasy(navColumn == null, "OneToOne navigation configuration error", $"OneToOne导航配置错误: 实体{listItemEntity.EntityName} 不存在{navObjectNameColumnInfo.Navigat.Name}"); + if (navColumn == null) { throw new SqlSugarLangException("OneToOne navigation configuration error", $"OneToOne导航配置错误: 实体{listItemEntity.EntityName} 不存在{navObjectNameColumnInfo.Navigat.Name}"); } var navType = navObjectNameProperty.PropertyType; navEntityInfo = context.EntityMaintenance.GetEntityInfo(navType); context.InitMappingInfo(navEntityInfo.Type); navPkColumn = navEntityInfo.Columns.Where(it => it.IsPrimarykey).FirstOrDefault(); - Check.ExceptionEasy(navPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null, navEntityInfo.EntityName + "need primarykey", navEntityInfo.EntityName + " 需要主键"); + if (navPkColumn == null && navObjectNameColumnInfo.Navigat.Name2 == null) { throw new SqlSugarLangException(navEntityInfo.EntityName + "need primarykey", navEntityInfo.EntityName + " 需要主键"); } if (navObjectNameColumnInfo.Navigat.Name2.HasValue()) { navPkColumn = navEntityInfo.Columns.Where(it => it.PropertyName == navObjectNameColumnInfo.Navigat.Name2).FirstOrDefault(); @@ -707,7 +707,7 @@ namespace ThingsGateway.SqlSugar } object reval = null; FieldInfo field = (FieldInfo)memberExpr.Member; - Check.Exception(field.IsPrivate, string.Format(" Field \"{0}\" can't be private ", field.Name)); + if (field.IsPrivate) { throw new SqlSugarException(string.Format(" Field \"{0}\" can't be private ", field.Name)); } reval = field.GetValue(memberExpr.Member); if (reval?.GetType().IsClass() == true && reval.GetType() != UtilConstants.StringType) { @@ -724,7 +724,7 @@ namespace ThingsGateway.SqlSugar } if (fieInfo == null && proInfo == null) { - Check.Exception(field.IsPrivate, string.Format(" Field \"{0}\" can't be private ", field.Name)); + if (field.IsPrivate) { throw new SqlSugarException(string.Format(" Field \"{0}\" can't be private ", field.Name)); } } } return reval; @@ -775,7 +775,7 @@ namespace ThingsGateway.SqlSugar } if (fieInfo == null && proInfo == null && !reval.GetType().FullName.IsCollectionsList()) { - Check.Exception(true, string.Format(" Property \"{0}\" can't be private ", pro.Name)); + { throw new SqlSugarException(string.Format(" Property \"{0}\" can't be private ", pro.Name)); } } } return reval; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/SugarParameter.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/SugarParameter.cs index d1ad55ae7..73d0e028d 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/SugarParameter.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Common/SugarParameter.cs @@ -1,5 +1,8 @@ using System.Data; using System.Data.Common; +using System.Numerics; + +using ThingsGateway.NewLife.Reflection; namespace ThingsGateway.SqlSugar { public class SugarParameter : DbParameter @@ -227,8 +230,20 @@ namespace ThingsGateway.SqlSugar _Size = -1; else { - var length = Value.ToString().Length; - _Size = length < 4000 ? 4000 : -1; + if (Value is DateTime) + { + _Size = 4000; + } + else if (Value.GetType().IsNumber()) + { + _Size = 4000; + } + else + { + var length = Value.ToString().Length; + _Size = length < 4000 ? 4000 : -1; + } + } } if (_Size == 0) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ExpressionContext.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ExpressionContext.cs index fe28caeec..0540defac 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ExpressionContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ExpressionContext.cs @@ -155,7 +155,7 @@ namespace ThingsGateway.SqlSugar public virtual string GetLimit() { return null; } public virtual string GetTranslationTableName(string entityName, bool isMapping = true) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } if (IsTranslationText(entityName)) return entityName; isMapping = isMapping && this.MappingTables.HasValue(); var isComplex = entityName.Contains(UtilConstants.Dot); @@ -197,7 +197,7 @@ namespace ThingsGateway.SqlSugar } public virtual string GetTranslationColumnName(string columnName) { - Check.ArgumentNullException(columnName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (columnName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } if (columnName.Substring(0, 1) == this.SqlParameterKeyWord || columnName.Substring(0, 1) == "@") { return columnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/BaseResolve_Append.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/BaseResolve_Append.cs index c72ed6b47..6045cdced 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/BaseResolve_Append.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/BaseResolve_Append.cs @@ -179,7 +179,7 @@ namespace ThingsGateway.SqlSugar } else if (parameter?.BaseParameter?.CommonTempData.ObjToString() == "IsJson=true") { - this.Context.Parameters.Add(new SugarParameter(appendValue, new SerializeService().SerializeObject(value)) { IsJson = true }); + this.Context.Parameters.Add(new SugarParameter(appendValue, DefaultServices.Serialize.SerializeObject(value)) { IsJson = true }); } else if (parameter?.BaseParameter?.CommonTempData.ObjToString() == "IsArray=true") { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/CoalesceResolveItems.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/CoalesceResolveItems.cs index 34d8fdcea..59d76d982 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/CoalesceResolveItems.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/CoalesceResolveItems.cs @@ -19,7 +19,7 @@ namespace ThingsGateway.SqlSugar { case ResolveExpressType.WhereSingle: case ResolveExpressType.WhereMultiple: - Check.Exception(name == "GetSelfAndAutoFill", "SqlFunc.GetSelfAndAutoFill can only be used in Select."); + if (name == "GetSelfAndAutoFill") { throw new SqlSugarException("SqlFunc.GetSelfAndAutoFill can only be used in Select."); } base.Where(parameter, isLeft, name, args, model); break; case ResolveExpressType.SelectSingle: diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/ConditionalExpressionResolve.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/ConditionalExpressionResolve.cs index 1519133cd..a92c159c4 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/ConditionalExpressionResolve.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/ConditionalExpressionResolve.cs @@ -68,7 +68,7 @@ namespace ThingsGateway.SqlSugar { case ResolveExpressType.WhereSingle: case ResolveExpressType.WhereMultiple: - Check.Exception(name == "GetSelfAndAutoFill", "SqlFunc.GetSelfAndAutoFill can only be used in Select."); + if (name == "GetSelfAndAutoFill") { throw new SqlSugarException("SqlFunc.GetSelfAndAutoFill can only be used in Select."); } base.Where(parameter, isLeft, name, args, model); break; case ResolveExpressType.SelectSingle: diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MapperExpressionResolve.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MapperExpressionResolve.cs index 1ce40bed4..459cd1e17 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MapperExpressionResolve.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MapperExpressionResolve.cs @@ -312,11 +312,11 @@ namespace ThingsGateway.SqlSugar void Error01() { - Check.Exception(mappers == null, ErrorMessage.GetThrowMessage(expression.ToString() + "no support Check if the navigation is configured correctly or Includes() is missing", "当前表达式" + expression.ToString() + " 不支持,查看导航是否配置正确等或者缺少Includes() ")); + if (mappers == null) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(expression.ToString() + "no support Check if the navigation is configured correctly or Includes() is missing", "当前表达式" + expression.ToString() + " 不支持,查看导航是否配置正确等或者缺少Includes() ")); } } void ThrowTrue(bool isError) { - Check.Exception(isError, ErrorMessage.GetThrowMessage(expression.ToString() + "no support Check if the navigation is configured correctly or Includes() is missing", "不支持表达式" + expression.ToString() + " ,查看导航是否配置正确等或者缺少Includes() ")); + if (isError) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(expression.ToString() + "no support Check if the navigation is configured correctly or Includes() is missing", "不支持表达式" + expression.ToString() + " ,查看导航是否配置正确等或者缺少Includes() ")); } } } } \ No newline at end of file diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberExpressionResolve.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberExpressionResolve.cs index e1538a0b2..f57d01d0b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberExpressionResolve.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberExpressionResolve.cs @@ -433,7 +433,7 @@ namespace ThingsGateway.SqlSugar } catch { - Check.Exception(true, "Not Support {0}", expression.ToString()); + { throw new SqlSugarException("Not Support {0}", expression.ToString()); } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberInitExpressionResolve.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberInitExpressionResolve.cs index 7b84cb25e..252e6b332 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberInitExpressionResolve.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MemberInitExpressionResolve.cs @@ -54,7 +54,7 @@ namespace ThingsGateway.SqlSugar if (columnInfo?.IsJson ?? false) { var paramterValue = ExpressionTool.DynamicInvoke(item); - var parameterName = AppendParameter(new SerializeService().SerializeObject(paramterValue)); + var parameterName = AppendParameter(DefaultServices.Serialize.SerializeObject(paramterValue)); var parameterObj = this.Context.Parameters.FirstOrDefault(it => it.ParameterName == parameterName); if (parameterObj != null) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs index a5b0724da..766ef84df 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve.cs @@ -47,7 +47,7 @@ namespace ThingsGateway.SqlSugar } else if (IsSubMethod(express, methodName)) { - //Check.Exception(!(parameter.BaseExpression is BinaryExpression), "Current expressions are not supported"); + //if(!(parameter.BaseExpression is BinaryExpression)){throw new SqlSugarException("Current expressions are not supported");} SubResolve subResolve = new SubResolve(express, this.Context, parameter.OppsiteExpression); var appendSql = subResolve.GetSql(); if (this.Context.ResolveType.IsIn(ResolveExpressType.SelectMultiple, ResolveExpressType.SelectSingle) || (parameter.BaseParameter != null && parameter.BaseParameter.CommonTempData?.Equals(CommonTempDataType.Result) == true)) @@ -180,7 +180,7 @@ namespace ThingsGateway.SqlSugar { case ResolveExpressType.WhereSingle: case ResolveExpressType.WhereMultiple: - Check.Exception(name == "GetSelfAndAutoFill", "SqlFunc.GetSelfAndAutoFill can only be used in Select."); + if (name == "GetSelfAndAutoFill") { throw new SqlSugarException("SqlFunc.GetSelfAndAutoFill can only be used in Select."); } if (name == "CharIndexNew" && args.Count == 1) { args.Insert(0, express.Object); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve_Helper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve_Helper.cs index 95bed3994..be4edc194 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve_Helper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/MethodCallExpressionResolve_Helper.cs @@ -57,11 +57,11 @@ namespace ThingsGateway.SqlSugar { if (ex is SqlSugarException) { - Check.Exception(true, string.Format(ex.Message, express.Method.Name)); + { throw new SqlSugarException(string.Format(ex.Message, express.Method.Name)); } } else { - Check.Exception(true, ErrorMessage.MethodError, express.Method.Name); + { throw new SqlSugarException(ErrorMessage.MethodError, express.Method.Name); } } } } @@ -369,7 +369,7 @@ namespace ThingsGateway.SqlSugar } private void AppendModelByIIFBinary(ExpressionParameter parameter, MethodCallExpressionModel model, Expression item) { - Check.Exception(true, "The SqlFunc.IIF(arg1,arg2,arg3) , {0} argument do not support ", item.ToString()); + { throw new SqlSugarException("The SqlFunc.IIF(arg1,arg2,arg3) , {0} argument do not support ", item.ToString()); } } private void AppendModelByIIFMethod(ExpressionParameter parameter, MethodCallExpressionModel model, Expression item) { @@ -385,7 +385,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, "The SqlFunc.IIF(arg1,arg2,arg3) , {0} argument do not support ", item.ToString()); + { throw new SqlSugarException("The SqlFunc.IIF(arg1,arg2,arg3) , {0} argument do not support ", item.ToString()); } } } @@ -549,7 +549,7 @@ namespace ThingsGateway.SqlSugar code = ExpressionTool.GetExpressionValue(express.Arguments[1]) + ""; } var entityDb = SqlFuncExtendsion.TableInfos.FirstOrDefault(y => y.Type.Name == name && y.Code == code); - Check.Exception(entityDb == null, string.Format("GetConfigValue no configuration Entity={0} UniqueCode={1}", name, code)); + if (entityDb == null) { throw new SqlSugarException(string.Format("GetConfigValue no configuration Entity={0} UniqueCode={1}", name, code)); } var entity = new ConfigTableInfo() { Code = entityDb.Code, @@ -798,7 +798,7 @@ namespace ThingsGateway.SqlSugar if (dateString2 != null) return dateString2; return GeDateFormat(model.Args.Last().MemberValue.ObjToString(), model.Args[0].MemberName.ObjToString()); } - //Check.Exception(model.Args.Count > 1, "ToString (Format) is not supported, Use ToString().If time formatting can be used it.Date.Year+\"-\"+it.Data.Month+\"-\"+it.Date.Day "); + //if(model.Args.Count > 1){throw new SqlSugarException("ToString (Format) is not supported, Use ToString().If time formatting can be used it.Date.Year+\"-\"+it.Data.Month+\"-\"+it.Date.Day ");} return this.Context.DbMehtods.ToString(model); case "ToVarchar": return this.Context.DbMehtods.ToVarchar(model); @@ -847,7 +847,7 @@ namespace ThingsGateway.SqlSugar return model.Args[0].MemberName.ObjToString().TrimStart('\'').TrimEnd('\''); } var isValid = model.Args[0].IsMember && model.Args[1].IsMember == false; - //Check.Exception(!isValid, "SqlFunc.MappingColumn parameters error, The property name on the left, string value on the right"); + //if(!isValid){throw new SqlSugarException("SqlFunc.MappingColumn parameters error, The property name on the left, string value on the right");} if (model.Args.Count > 1) { this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[1].MemberName.ObjToString()); @@ -1077,7 +1077,7 @@ namespace ThingsGateway.SqlSugar { if (expression?.Object?.Type?.Name?.StartsWith("ISugarQueryable`") == true) { - Check.ExceptionEasy("Sublookup is implemented using SqlFunc.Subquery(); Queryable objects cannot be used", "子查请使用SqlFunc.Subquery()来实现,不能用Queryable对象"); + Check.ExceptionLang("Sublookup is implemented using SqlFunc.Subquery(); Queryable objects cannot be used", "子查请使用SqlFunc.Subquery()来实现,不能用Queryable对象"); } if (expression.Method.Name == "SelectAll") { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/NewExpressionResolve.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/NewExpressionResolve.cs index 072c66957..ab4fb8036 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/NewExpressionResolve.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/NewExpressionResolve.cs @@ -21,11 +21,11 @@ namespace ThingsGateway.SqlSugar Check.ThrowNotSupportedException(expression.ToString()); break; case ResolveExpressType.SelectSingle: - Check.Exception(expression.Type == UtilConstants.DateType, "ThrowNotSupportedException {0} ", expression.ToString()); + if (expression.Type == UtilConstants.DateType) { throw new SqlSugarException("ThrowNotSupportedException {0} ", expression.ToString()); } Select(expression, parameter, true); break; case ResolveExpressType.SelectMultiple: - Check.Exception(expression.Type == UtilConstants.DateType, "ThrowNotSupportedException {0} ", expression.ToString()); + if (expression.Type == UtilConstants.DateType) { throw new SqlSugarException("ThrowNotSupportedException {0} ", expression.ToString()); } Select(expression, parameter, false); break; case ResolveExpressType.FieldSingle: @@ -128,7 +128,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(expression.Type == UtilConstants.DateType, "ThrowNotSupportedException {0} ", ex.ToString()); + if (expression.Type == UtilConstants.DateType) { throw new SqlSugarException("ThrowNotSupportedException {0} ", ex.ToString()); } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpression.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpression.cs index aa92d1d3d..d555fc614 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpression.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpression.cs @@ -146,10 +146,9 @@ namespace ThingsGateway.SqlSugar { if (Navigat.Name == null) { - Check.ExceptionEasy( - true, - " NavigateType.Dynamic User-defined navigation objects need to be configured with json to be used in expressions . " + this.ProPertyEntity.Type.Name, - " NavigateType.Dynamic 自定义导航对象需要配置json才能在表达式中使用。 " + this.ProPertyEntity.Type.Name); + throw new SqlSugarLangException( + " NavigateType.Dynamic User-defined navigation objects need to be configured with json to be used in expressions . " + this.ProPertyEntity.Type.Name, + " NavigateType.Dynamic 自定义导航对象需要配置json才能在表达式中使用。 " + this.ProPertyEntity.Type.Name); } MapperSql mapper = new MapperSql(); var queryable = this.context.Queryable(); @@ -212,14 +211,14 @@ namespace ThingsGateway.SqlSugar { aPk = this.EntityInfo.Columns.FirstOrDefault(it => it.PropertyName == Navigat.AClassId)?.DbColumnName; } - Check.ExceptionEasy(aPk.IsNullOrEmpty(), $"{this.EntityInfo.EntityName}need primary key", $"{this.EntityInfo.EntityName}需要主键"); - Check.ExceptionEasy(bPk.IsNullOrEmpty(), $"{this.ProPertyEntity.EntityName}need primary key", $"{this.ProPertyEntity.EntityName}需要主键"); + if (aPk.IsNullOrEmpty()) { throw new SqlSugarLangException($"{this.EntityInfo.EntityName}need primary key", $"{this.EntityInfo.EntityName}需要主键"); } + if (bPk.IsNullOrEmpty()) { throw new SqlSugarLangException($"{this.ProPertyEntity.EntityName}need primary key", $"{this.ProPertyEntity.EntityName}需要主键"); } MapperSql mapper = new MapperSql(); var queryable = this.context.Queryable(); bPk = queryable.QueryBuilder.Builder.GetTranslationColumnName(bPk); aPk = queryable.QueryBuilder.Builder.GetTranslationColumnName(aPk); var mappingType = Navigat.MappingType; - Check.ExceptionEasy(mappingType == null, "ManyToMany misconfiguration", "多对多配置错误"); + if (mappingType == null) { throw new SqlSugarLangException("ManyToMany misconfiguration", "多对多配置错误"); } var mappingEntity = this.context.EntityMaintenance.GetEntityInfo(mappingType); var mappingTableName = queryable.QueryBuilder.Builder.GetTranslationTableName(mappingEntity.DbTableName); var mappingA = mappingEntity.Columns.First(it => it.PropertyName == Navigat.MappingAId).DbColumnName; @@ -276,8 +275,12 @@ namespace ThingsGateway.SqlSugar { pkColumn = this.EntityInfo.Columns.FirstOrDefault(it => it.PropertyName == Navigat.Name2); } - Check.ExceptionEasy(pkColumn == null, $"{this.EntityInfo.EntityName} need primary key ", - $"导航属性 {this.EntityInfo.EntityName}需要主键"); + + if (pkColumn == null) + { + throw new SqlSugarLangException($"{this.EntityInfo.EntityName} need primary key ", + $"导航属性 {this.EntityInfo.EntityName}需要主键"); + } var pk = pkColumn.DbColumnName; var name = this.ProPertyEntity.Columns.First(it => it.PropertyName == Navigat.Name).DbColumnName; //var selectName = this.ProPertyEntity.Columns.First(it => it.PropertyName == MemberName).DbColumnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpressionN.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpressionN.cs index 7626afee7..7302e5fea 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpressionN.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToManyNavgateExpressionN.cs @@ -122,9 +122,9 @@ namespace ThingsGateway.SqlSugar var last = subInfos[0]; var FirstPkColumn = last.ThisEntityInfo.Columns.FirstOrDefault(it => it.IsPrimarykey); FirstPkColumn = GetFirstPkColumn(last, FirstPkColumn); - Check.ExceptionEasy(FirstPkColumn == null, $"{last.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{last.ThisEntityInfo.EntityName} 缺少主键"); + if (FirstPkColumn == null) { throw new SqlSugarLangException($"{last.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{last.ThisEntityInfo.EntityName} 缺少主键"); } var PkColumn = last.ParentEntityInfo.Columns.FirstOrDefault(it => it.PropertyName == last.Nav.Name); - Check.ExceptionEasy(PkColumn == null, $"{last.ParentEntityInfo.EntityName} no found {last.Nav.Name}", $"{last.ParentEntityInfo.EntityName} 不存在 {last.Nav.Name}"); + if (PkColumn == null) { throw new SqlSugarLangException($"{last.ParentEntityInfo.EntityName} no found {last.Nav.Name}", $"{last.ParentEntityInfo.EntityName} 不存在 {last.Nav.Name}"); } queryable.Where($" {queryable.SqlBuilder.GetTranslationColumnName(this.shorName)}.{queryable.SqlBuilder.GetTranslationColumnName(PkColumn.DbColumnName)} = {queryable.SqlBuilder.GetTranslationColumnName(masterShortName)}.{queryable.SqlBuilder.GetTranslationColumnName(FirstPkColumn.DbColumnName)} "); queryable.WhereIF(this.whereSql.HasValue(), GetWhereSql1(this.whereSql, lastShortName, joinInfos, queryable.SqlBuilder)); MapperSql.Sql = $"( {queryable.ToSql().Key} ) "; @@ -175,7 +175,7 @@ namespace ThingsGateway.SqlSugar // pkColumn = item.ThisEntityInfo.Columns.FirstOrDefault(it => it.IsPrimarykey); // navColum = item.ParentEntityInfo.Columns.FirstOrDefault(it => it.PropertyName == item.Nav.Name); //} - Check.ExceptionEasy(pkColumn == null, $"{item.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{item.ThisEntityInfo.EntityName} 缺少主键"); + if (pkColumn == null) { throw new SqlSugarLangException($"{item.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{item.ThisEntityInfo.EntityName} 缺少主键"); } var on = $" {queryable.SqlBuilder.GetTranslationColumnName(shortName)}.{queryable.SqlBuilder.GetTranslationColumnName(pkColumn.DbColumnName)}={queryable.SqlBuilder.GetTranslationColumnName(formInfo.ThisEntityInfo.DbTableName + (i - 1))}.{queryable.SqlBuilder.GetTranslationColumnName(navColum.DbColumnName)}"; queryable.AddJoinInfo(item.ThisEntityInfo.DbTableName, shortName, on, JoinType.Inner); ++i; @@ -205,7 +205,7 @@ namespace ThingsGateway.SqlSugar pkColumn = item.ThisEntityInfo.Columns.FirstOrDefault(it => it.PropertyName == item.Nav.Name2); } //} - Check.ExceptionEasy(pkColumn == null, $"{item.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{item.ThisEntityInfo.EntityName} 缺少主键"); + if (pkColumn == null) { throw new SqlSugarLangException($"{item.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{item.ThisEntityInfo.EntityName} 缺少主键"); } var on = $" {shortName}.{queryable.SqlBuilder.GetTranslationColumnName(pkColumn.DbColumnName)}={formInfo.ThisEntityInfo.DbTableName + (i - 1)}.{queryable.SqlBuilder.GetTranslationColumnName(navColum.DbColumnName)}"; queryable.AddJoinInfo(item.ThisEntityInfo.DbTableName, shortName, on, JoinType.Inner); ++i; @@ -229,8 +229,8 @@ namespace ThingsGateway.SqlSugar var Ab_Aid = abEntity.Columns.FirstOrDefault(it => item.Nav.MappingAId == it.PropertyName); var Ab_Bid = abEntity.Columns.FirstOrDefault(it => item.Nav.MappingBId == it.PropertyName); - Check.ExceptionEasy(AidColumn == null, $" {AidColumn.EntityName} need primary key ", $"{AidColumn.EntityName}需要主键"); - Check.ExceptionEasy(AidColumn == null, $" {BidColumn.EntityName} need primary key ", $"{BidColumn.EntityName}需要主键"); + if (AidColumn == null) { throw new SqlSugarLangException($" {AidColumn.EntityName} need primary key ", $"{AidColumn.EntityName}需要主键"); } + if (AidColumn == null) { throw new SqlSugarLangException($" {BidColumn.EntityName} need primary key ", $"{BidColumn.EntityName}需要主键"); } var abShort = abEntity.EntityName + "_1"; var abOn = $" {queryable.SqlBuilder.GetTranslationColumnName(abShort)}.{queryable.SqlBuilder.GetTranslationColumnName(Ab_Aid.DbColumnName)}={formInfo.ThisEntityInfo.DbTableName + (i - 1)}.{queryable.SqlBuilder.GetTranslationColumnName(AidColumn.DbColumnName)}"; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpression.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpression.cs index 3124527f1..55a14d8bd 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpression.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpression.cs @@ -67,7 +67,7 @@ namespace ThingsGateway.SqlSugar { if (this.ProPertyEntity.Type.Name.StartsWith("List`")) { - Check.ExceptionEasy(true, " expression error ", "导航查询出错,比如.Count要改成 .Count()"); + if (true) { throw new SqlSugarLangException(" expression error ", "导航查询出错,比如.Count要改成 .Count()"); } } else if (Navigat.NavigatType == NavigateType.Dynamic) { @@ -80,8 +80,7 @@ namespace ThingsGateway.SqlSugar } if (pk == null) { - Check.ExceptionEasy( - true, + throw new SqlSugarLangException( $"{this.ProPertyEntity.EntityName} naviate config error", $"{this.ProPertyEntity.EntityName} 导航配置错误"); } @@ -153,8 +152,7 @@ namespace ThingsGateway.SqlSugar { if (Navigat.Name == null) { - Check.ExceptionEasy( - true, + throw new SqlSugarLangException( " NavigateType.Dynamic User-defined navigation objects need to be configured with json to be used in expressions . " + this.ProPertyEntity.Type.Name, " NavigateType.Dynamic 自定义导航对象需要配置json才能在表达式中使用。 " + this.ProPertyEntity.Type.Name); } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpressionN.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpressionN.cs index b189f4416..f10b7f52a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpressionN.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/ResolveItems/OneToOneNavgateExpressionN.cs @@ -62,7 +62,7 @@ namespace ThingsGateway.SqlSugar } } var navColum = item.ParentEntityInfo.Columns.FirstOrDefault(it => it.PropertyName == item.Nav.Name); - Check.ExceptionEasy(pkColumn == null, $"{item.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{item.ThisEntityInfo.EntityName} 缺少主键"); + if (pkColumn == null) { throw new SqlSugarLangException($"{item.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{item.ThisEntityInfo.EntityName} 缺少主键"); } var on = $" {ToShortName(shortName)}.{queryable.SqlBuilder.GetTranslationColumnName(pkColumn.DbColumnName)}={ToShortName(formInfo.ThisEntityInfo.DbTableName + (i - 1))}.{queryable.SqlBuilder.GetTranslationColumnName(navColum.DbColumnName)}"; if (item.Nav.WhereSql.HasValue()) { @@ -90,9 +90,9 @@ namespace ThingsGateway.SqlSugar FirstPkColumn = nav2; } } - Check.ExceptionEasy(FirstPkColumn == null, $"{last.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{last.ThisEntityInfo.EntityName} 缺少主键"); + if (FirstPkColumn == null) { throw new SqlSugarLangException($"{last.ThisEntityInfo.EntityName} need PrimayKey", $"使用导航属性{last.ThisEntityInfo.EntityName} 缺少主键"); } var PkColumn = last.ParentEntityInfo.Columns.FirstOrDefault(it => it.PropertyName == last.Nav.Name); - Check.ExceptionEasy(PkColumn == null, $"{last.ParentEntityInfo.EntityName} no found {last.Nav.Name}", $"{last.ParentEntityInfo.EntityName} 不存在 {last.Nav.Name}"); + if (PkColumn == null) { throw new SqlSugarLangException($"{last.ParentEntityInfo.EntityName} no found {last.Nav.Name}", $"{last.ParentEntityInfo.EntityName} 不存在 {last.Nav.Name}"); } queryable.Where($" {ToShortName(this.shorName)}.{queryable.SqlBuilder.GetTranslationColumnName(PkColumn.DbColumnName)} = {ToShortName(masterShortName)}.{queryable.SqlBuilder.GetTranslationColumnName(FirstPkColumn.DbColumnName)} "); MapperSql.Sql = "( " + queryable.ToSql().Key + " ) "; return MapperSql; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubAndIF.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubAndIF.cs index aa7d50b5a..30b2f90e9 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubAndIF.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubAndIF.cs @@ -42,7 +42,7 @@ namespace ThingsGateway.SqlSugar } catch { - Check.Exception(true, ErrorMessage.WhereIFCheck, exp.Arguments[0].ToString()); + { throw new SqlSugarException(ErrorMessage.WhereIFCheck, exp.Arguments[0].ToString()); } } var isWhere = Convert.ToBoolean(value); if (!Convert.ToBoolean(isWhere)) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubFirst.cs index 646788c99..9c6344828 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubFirst.cs @@ -134,7 +134,7 @@ namespace ThingsGateway.SqlSugar { this.Context.CurrentShortName = this.Context.GetTranslationColumnName(parameters.FirstOrDefault().Name); } - Check.ExceptionEasy(newMemExp == null, $"Subquery ToList(exp,true) expression {exp.ToString()} can only be it=>new class(){{Id = it.id}}", $"子查询ToList(exp,true)表达式{exp.ToString()}只能是it=>new class(){{ id=it.Id}}"); + if (newMemExp == null) { throw new SqlSugarLangException($"Subquery ToList(exp,true) expression {exp.ToString()} can only be it=>new class(){{Id = it.id}}", $"子查询ToList(exp,true)表达式{exp.ToString()}只能是it=>new class(){{ id=it.Id}}"); } var dic = ExpressionTool.GetMemberBindingItemList(newMemExp.Bindings); var db = this.Context.SugarContext.Context; var builder = this.Context.SugarContext.QueryBuilder.Builder; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubToList.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubToList.cs index 329f2ffe8..57b7735e3 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubToList.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubToList.cs @@ -135,7 +135,7 @@ namespace ThingsGateway.SqlSugar { this.Context.CurrentShortName = this.Context.GetTranslationColumnName(parameters.FirstOrDefault().Name); } - Check.ExceptionEasy(newMemExp == null, $"Subquery ToList(exp,true) expression {exp.ToString()} can only be it=>new class(){{Id = it.id}}", $"子查询ToList(exp,true)表达式{exp.ToString()}只能是it=>new class(){{ id=it.Id}}"); + if (newMemExp == null) { throw new SqlSugarLangException($"Subquery ToList(exp,true) expression {exp.ToString()} can only be it=>new class(){{Id = it.id}}", $"子查询ToList(exp,true)表达式{exp.ToString()}只能是it=>new class(){{ id=it.Id}}"); } var dic = ExpressionTool.GetMemberBindingItemList(newMemExp.Bindings); var db = this.Context.SugarContext.Context; var builder = this.Context.SugarContext.QueryBuilder.Builder; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubWhereIF.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubWhereIF.cs index d5ef9c8ca..41d78b58f 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubWhereIF.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/Items/SubWhereIF.cs @@ -45,7 +45,7 @@ namespace ThingsGateway.SqlSugar } catch { - Check.Exception(true, ErrorMessage.WhereIFCheck, exp.Arguments[0].ToString()); + { throw new SqlSugarException(ErrorMessage.WhereIFCheck, exp.Arguments[0].ToString()); } } if (_regex.Count(expression.ToString()) >= 2) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/SubResolve.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/SubResolve.cs index cef739842..42e7182aa 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/SubResolve.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExpressionsToSql/Subquery/SubResolve.cs @@ -125,7 +125,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.ExceptionEasy("I'm sorry I can't parse the current expression", "不支持当前表达式"); + Check.ExceptionLang("I'm sorry I can't parse the current expression", "不支持当前表达式"); } } var subIndex = this.context.SubQueryIndex; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExternalServiceInterface/ISerializeService.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExternalServiceInterface/ISerializeService.cs index 889b62553..689e71bef 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/ExternalServiceInterface/ISerializeService.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/ExternalServiceInterface/ISerializeService.cs @@ -3,7 +3,6 @@ public interface ISerializeService { string SerializeObject(object value); - string SugarSerializeObject(object value); T DeserializeObject(string value); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/ContextMethods.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/ContextMethods.cs index 1f930ec3a..a3c9e4ddf 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/ContextMethods.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/ContextMethods.cs @@ -912,15 +912,15 @@ namespace ThingsGateway.SqlSugar } else { - var isSugar = this.Context.EntityMaintenance.GetEntityInfo(type).Columns.Any(it => it.NoSerialize || it.SerializeDateTimeFormat.HasValue()); - if (isSugar) - { - return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.SugarSerializeObject(value); - } - else - { - return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.SerializeObject(value); - } + //var isSugar = this.Context.EntityMaintenance.GetEntityInfo(type).Columns.Any(it => it.NoSerialize || it.SerializeDateTimeFormat.HasValue()); + //if (isSugar) + //{ + // return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.SugarSerializeObject(value); + //} + //else + //{ + return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.SerializeObject(value); + //} } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/DependencyManagement.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/DependencyManagement.cs index 9bd8d19cb..f1ad0ad10 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/DependencyManagement.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/DependencyManagement.cs @@ -16,7 +16,7 @@ { try { - new SerializeService().SerializeObject(new { }); + DefaultServices.Serialize.SerializeObject(new { }); IsTryJsonNet = true; } catch diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/InstanceFactory.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/InstanceFactory.cs index d0842e3eb..36cedbeca 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/InstanceFactory.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Infrastructure/InstanceFactory.cs @@ -573,7 +573,7 @@ namespace ThingsGateway.SqlSugar type = Type.GetType(className + '`' + types.Length, true).MakeGenericType(types); } } - Check.ArgumentNullException(type, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, className)); + if (type == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, className)); } typeCache.TryAdd(cacheKey, type); } } @@ -653,7 +653,7 @@ namespace ThingsGateway.SqlSugar { type = GetCustomDbType(className, type); } - Check.ArgumentNullException(type, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, className)); + if (type == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, className)); } typeCache.TryAdd(className, type); } } @@ -755,8 +755,7 @@ namespace ThingsGateway.SqlSugar catch { var message = "Not Found " + customDllName + ".dll"; - Check.Exception(true, message); - return null; + { throw new SqlSugarException(message); } } }); Type type = newAssembly.GetType(className); @@ -810,8 +809,7 @@ namespace ThingsGateway.SqlSugar catch { var message = "Not Found " + customDllName + ".dll"; - Check.Exception(true, message); - return null; + { throw new SqlSugarException(message); } } }); Type typeArgument = typeof(T); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SerializeService.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SerializeService.cs index f9a27d898..0599bdfc0 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SerializeService.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SerializeService.cs @@ -1,5 +1,12 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; + +using System.Collections.Concurrent; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; using JsonProperty = Newtonsoft.Json.Serialization.JsonProperty; @@ -11,45 +18,96 @@ namespace ThingsGateway.SqlSugar { NullValueHandling = NullValueHandling.Ignore, - ContractResolver = new MyContractResolver() + ContractResolver = new NewtonsoftResolver() }; + private static readonly JsonSerializerOptions _systemTextJsonSettings = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + private static readonly ConcurrentDictionary _typeInfoCache = new(); + + static SerializeService() + { + var resolver = new DefaultJsonTypeInfoResolver + { + }; + resolver.Modifiers.Add( + ti => + { + foreach (var prop in ti.Properties) + { + var sugar = _typeInfoCache.GetOrAdd(prop.PropertyType, t => t.GetCustomAttribute(true)); + if (sugar?.NoSerialize == true) + { + prop.ShouldSerialize = static (obj, propInfo) => false; + } + + if (prop.PropertyType == typeof(DateTime) && !string.IsNullOrEmpty(sugar?.SerializeDateTimeFormat)) + { + prop.CustomConverter = new SystemTextJsonDateTimeJsonConverter(sugar.SerializeDateTimeFormat); + } + + } + }); + _systemTextJsonSettings.TypeInfoResolver = resolver; + } + public static bool UseNewtonsoftJson = false; + + + public string SerializeObject(object value) { if (value == null) return "null"; - // 精准类型检查(避免反射) - return value switch + switch (value) { - System.Text.Json.JsonElement element => System.Text.Json.JsonSerializer.Serialize(element), - System.Text.Json.JsonDocument document => System.Text.Json.JsonSerializer.Serialize(document), - System.Text.Json.Nodes.JsonValue valueType => System.Text.Json.JsonSerializer.Serialize(valueType), - _ => JsonConvert.SerializeObject(value, _newtonsoftSettings) - }; + case System.Text.Json.JsonElement element: + return System.Text.Json.JsonSerializer.Serialize(element, _systemTextJsonSettings); + case System.Text.Json.JsonDocument document: + return System.Text.Json.JsonSerializer.Serialize(document, _systemTextJsonSettings); + case System.Text.Json.Nodes.JsonValue valueType: + return System.Text.Json.JsonSerializer.Serialize(valueType, _systemTextJsonSettings); + case JToken jToken: + return JsonConvert.SerializeObject(jToken, _newtonsoftSettings); + + default: + if (UseNewtonsoftJson) + return JsonConvert.SerializeObject(value, _newtonsoftSettings); + else + return System.Text.Json.JsonSerializer.Serialize(value, value.GetType(), _systemTextJsonSettings); + } } - public string SugarSerializeObject(object value) - { - return JsonConvert.SerializeObject(value, _newtonsoftSettings); - } + private static readonly Type JsonElementType = typeof(System.Text.Json.JsonElement); private static readonly Type JsonDocumentType = typeof(System.Text.Json.JsonDocument); private static readonly Type JsonValueType = typeof(System.Text.Json.Nodes.JsonValue); + private static readonly Type JTokenType = typeof(JToken); public T DeserializeObject(string value) { var type = typeof(T); if (type == JsonElementType) - return System.Text.Json.JsonSerializer.Deserialize(value); + return System.Text.Json.JsonSerializer.Deserialize(value, _systemTextJsonSettings); else if (type == JsonDocumentType) - return System.Text.Json.JsonSerializer.Deserialize(value); + return System.Text.Json.JsonSerializer.Deserialize(value, _systemTextJsonSettings); else if (type == JsonValueType) - return System.Text.Json.JsonSerializer.Deserialize(value); - else + return System.Text.Json.JsonSerializer.Deserialize(value, _systemTextJsonSettings); + else if (JTokenType.IsAssignableFrom(type)) return JsonConvert.DeserializeObject(value, _newtonsoftSettings); + else + { + if (UseNewtonsoftJson) + return JsonConvert.DeserializeObject(value, _newtonsoftSettings); + else + return System.Text.Json.JsonSerializer.Deserialize(value, _systemTextJsonSettings); + } } } - public class MyContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver + public class NewtonsoftResolver : Newtonsoft.Json.Serialization.DefaultContractResolver { protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) { @@ -89,4 +147,228 @@ namespace ThingsGateway.SqlSugar } + + + + + + + + + + /// + /// DateTime 类型序列化 + /// + class SystemTextJsonDateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter + { + /// + /// 默认构造函数 + /// + public SystemTextJsonDateTimeJsonConverter() + : this(default) + { + } + + /// + /// 构造函数 + /// + /// + public SystemTextJsonDateTimeJsonConverter(string format = "yyyy-MM-dd HH:mm:ss") + { + Format = format; + } + + /// + /// 构造函数 + /// + /// + /// + public SystemTextJsonDateTimeJsonConverter(string format = "yyyy-MM-dd HH:mm:ss", bool outputToLocalDateTime = false) + : this(format) + { + Localized = outputToLocalDateTime; + } + + /// + /// 时间格式化格式 + /// + public string Format { get; private set; } + + /// + /// 是否输出为为当地时间 + /// + public bool Localized { get; private set; } = false; + + /// + /// 反序列化 + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return Penetrates.ConvertToDateTime(ref reader); + } + + /// + /// 序列化 + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + // 判断是否序列化成当地时间 + var formatDateTime = Localized ? value.ToLocalTime() : value; + writer.WriteStringValue(formatDateTime.ToString(Format)); + } + } + + /// + /// 常量、公共方法配置类 + /// + static class Penetrates + { + + /// + /// 将时间戳转换为 DateTime + /// + /// + /// + internal static DateTime ConvertToDateTime(this long timestamp) + { + var timeStampDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var digitCount = (int)Math.Floor(Math.Log10(timestamp) + 1); + + if (digitCount != 13 && digitCount != 10) + { + throw new ArgumentException("Data is not a valid timestamp format."); + } + + return (digitCount == 13 + ? timeStampDateTime.AddMilliseconds(timestamp) // 13 位时间戳 + : timeStampDateTime.AddSeconds(timestamp)).ToLocalTime(); // 10 位时间戳 + } + /// + /// 转换 + /// + /// + /// + internal static DateTime ConvertToDateTime(ref Utf8JsonReader reader) + { + // 处理时间戳自动转换 + if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var longValue)) + { + return longValue.ConvertToDateTime(); + } + + var stringValue = reader.GetString(); + + // 处理时间戳自动转换 + if (long.TryParse(stringValue, out var longValue2)) + { + return longValue2.ConvertToDateTime(); + } + + return Convert.ToDateTime(stringValue); + } + + /// + /// 转换 + /// + /// + /// + internal static DateTime ConvertToDateTime(ref JsonReader reader) + { + if (reader.TokenType == JsonToken.Integer) + { + return JValue.ReadFrom(reader).Value().ConvertToDateTime(); + } + + var stringValue = JValue.ReadFrom(reader).Value(); + + // 处理时间戳自动转换 + if (long.TryParse(stringValue, out var longValue2)) + { + return longValue2.ConvertToDateTime(); + } + + return Convert.ToDateTime(stringValue); + } + } + /// + /// DateTime? 类型序列化 + /// + + class SystemTextJsonNullableDateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter + { + /// + /// 默认构造函数 + /// + public SystemTextJsonNullableDateTimeJsonConverter() + : this(default) + { + } + + /// + /// 构造函数 + /// + /// + public SystemTextJsonNullableDateTimeJsonConverter(string format = "yyyy-MM-dd HH:mm:ss") + { + Format = format; + } + + /// + /// 构造函数 + /// + /// + /// + public SystemTextJsonNullableDateTimeJsonConverter(string format = "yyyy-MM-dd HH:mm:ss", bool outputToLocalDateTime = false) + : this(format) + { + Localized = outputToLocalDateTime; + } + + /// + /// 时间格式化格式 + /// + public string Format { get; private set; } + + /// + /// 是否输出为为当地时间 + /// + public bool Localized { get; private set; } = false; + + /// + /// 反序列化 + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return Penetrates.ConvertToDateTime(ref reader); + } + + /// + /// 序列化 + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) + { + if (value == null) writer.WriteNullValue(); + else + { + // 判断是否序列化成当地时间 + var formatDateTime = Localized ? value.Value.ToLocalTime() : value.Value; + writer.WriteStringValue(formatDateTime.ToString(Format)); + } + } + } + } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SplitTableService.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SplitTableService.cs index 2e63108b2..9a4b345d3 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SplitTableService.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/IntegrationServices/SplitTableService.cs @@ -188,13 +188,13 @@ namespace ThingsGateway.SqlSugar private static void CheckTableName(string dbTableName) { - Check.Exception(!dbTableName.Contains("{year}"), ErrorMessage.GetThrowMessage("table name need {{year}}", "分表表名需要占位符 {{year}}")); - Check.Exception(!dbTableName.Contains("{month}"), ErrorMessage.GetThrowMessage("table name need {{month}}", "分表表名需要占位符 {{month}} ")); - Check.Exception(!dbTableName.Contains("{day}"), ErrorMessage.GetThrowMessage("table name need {{day}}", "分表表名需要占位符{{day}}")); - Check.Exception(_yearRegex.Count(dbTableName) > 1, ErrorMessage.GetThrowMessage(" There can only be one {{year}}", " 只能有一个 {{year}}")); - Check.Exception(_monthRegex.Count(dbTableName) > 1, ErrorMessage.GetThrowMessage("There can only be one {{month}}", "只能有一个 {{month}} ")); - Check.Exception(_dayRegex.Count(dbTableName) > 1, ErrorMessage.GetThrowMessage("There can only be one {{day}}", "只能有一个{{day}}")); - Check.Exception(_regex.IsMatch(dbTableName), ErrorMessage.GetThrowMessage(" '{{' or '}}' can't be numbers nearby", "占位符相令一位不能是数字,比如 : 1{{day}}2 错误 , 正确: 1_{{day}}_2")); + if (!dbTableName.Contains("{year}")) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("table name need {{year}}", "分表表名需要占位符 {{year}}")); } + if (!dbTableName.Contains("{month}")) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("table name need {{month}}", "分表表名需要占位符 {{month}} ")); } + if (!dbTableName.Contains("{day}")) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("table name need {{day}}", "分表表名需要占位符{{day}}")); } + if (_yearRegex.Count(dbTableName) > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(" There can only be one {{year}}", " 只能有一个 {{year}}")); } + if (_monthRegex.Count(dbTableName) > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("There can only be one {{month}}", "只能有一个 {{month}} ")); } + if (_dayRegex.Count(dbTableName) > 1) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("There can only be one {{day}}", "只能有一个{{day}}")); } + if (_regex.IsMatch(dbTableName)) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(" '{{' or '}}' can't be numbers nearby", "占位符相令一位不能是数字,比如 : 1{{day}}2 错误 , 正确: 1_{{day}}_2")); } } #endregion @@ -204,43 +204,34 @@ namespace ThingsGateway.SqlSugar switch (type) { case SplitType.Day: - return Convert.ToDateTime(time.ToString("yyyy-MM-dd")); + return new DateTime(time.Year, time.Month, time.Day); + case SplitType.Week: return GetMondayDate(time); + case SplitType.Month: - return Convert.ToDateTime(time.ToString("yyyy-MM-01")); + return new DateTime(time.Year, time.Month, 1); + case SplitType.Season: - if (time.Month <= 3) { - return Convert.ToDateTime(time.ToString("yyyy-01-01")); - } - else if (time.Month <= 6) - { - return Convert.ToDateTime(time.ToString("yyyy-04-01")); - } - else if (time.Month <= 9) - { - return Convert.ToDateTime(time.ToString("yyyy-07-01")); - } - else - { - return Convert.ToDateTime(time.ToString("yyyy-10-01")); + int quarterStartMonth = time.Month - (time.Month - 1) % 3; + return new DateTime(time.Year, quarterStartMonth, 1); } + case SplitType.Year: - return Convert.ToDateTime(time.ToString("yyyy-01-01")); + return new DateTime(time.Year, 1, 1); + case SplitType.Month_6: - if (time.Month <= 6) { - return Convert.ToDateTime(time.ToString("yyyy-01-01")); - } - else - { - return Convert.ToDateTime(time.ToString("yyyy-07-01")); + int halfYearStartMonth = time.Month <= 6 ? 1 : 7; + return new DateTime(time.Year, halfYearStartMonth, 1); } + default: - throw new Exception($"SplitType parameter error "); + throw new ArgumentOutOfRangeException(nameof(type), $"SplitType parameter error: {type}"); } } + private DateTime GetMondayDate() { return GetMondayDate(DateTime.Now); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IFastBuilder.cs index 9d81c41b9..0cb8db02c 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IFastBuilder.cs @@ -11,8 +11,22 @@ namespace ThingsGateway.SqlSugar string CharacterSet { get; set; } Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns); Task ExecuteBulkCopyAsync(DataTable dt); + Task ExecuteBulkCopyAsync(string tableName, Dictionary)> list) + { + return Task.FromResult(0); + } Task CreateTempAsync(DataTable dt) where T : class, new(); + Task CreateTempAsync(Dictionary)> list) where T : class, new() + { + return Task.FromResult(string.Empty); + } + void CloseDb(); + + Task Merge(string tableName, Dictionary)> list, EntityInfo entityInfo, string[] whereColumns, string[] updateColumns, IEnumerable datas) where T : class, new() + { + return Task.FromResult(0); + } Task Merge(string tableName, DataTable dt, EntityInfo entityInfo, string[] whereColumns, string[] updateColumns, IEnumerable datas) where T : class, new(); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IStorageable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IStorageable.cs index 3217e864d..f1d9925e3 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IStorageable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Interface/IStorageable.cs @@ -1,4 +1,5 @@ -using System.Linq.Expressions; +using System.Diagnostics; +using System.Linq.Expressions; namespace ThingsGateway.SqlSugar { public interface IStorageable where T : class, new() @@ -94,17 +95,26 @@ namespace ThingsGateway.SqlSugar Other = 4, Ignore = 5, } - internal struct KeyValuePair + public readonly struct KeyValuePair { - public TKey key; - public TValue value1; - public TValue2 value2; - public KeyValuePair(TKey key, TValue value1, TValue2 value2) + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly TKey key; // Do not rename (binary serialization) + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly TValue value; // Do not rename (binary serialization) + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly TValue2 value2; // Do not rename (binary serialization) + public KeyValuePair(TKey key, TValue value, TValue2 value2) { this.key = key; - this.value1 = value1; + this.value = value; this.value2 = value2; } + + public TKey Key => key; + + public TValue Value => value; + public TValue2 Value2 => value2; + } public class StorageableResult where T : class, new() @@ -160,7 +170,7 @@ namespace ThingsGateway.SqlSugar } public int BulkUpdate(params string[] UpdateColumns) { - Check.Exception(UpdateColumns == null, "UpdateColumns is null"); + if (UpdateColumns == null) { throw new SqlSugarException("UpdateColumns is null"); } if (_WhereColumnList != null && _WhereColumnList.Count != 0) { return this._Context.Fastest().AS(_AsName).BulkUpdate(UpdateList.Select(it => it.Item).ToList(), _WhereColumnList.Select(it => it.DbColumnName).ToArray(), UpdateColumns); @@ -168,13 +178,13 @@ namespace ThingsGateway.SqlSugar else { var pkColumns = this._Context.EntityMaintenance.GetEntityInfo().Columns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName).ToArray(); - Check.Exception(pkColumns.Length == 0, "need primary key"); + if (pkColumns.Length == 0) { throw new SqlSugarException("need primary key"); } return this._Context.Fastest().AS(_AsName).BulkUpdate(UpdateList.Select(it => it.Item).ToList(), pkColumns, UpdateColumns); } } public async Task BulkUpdateAsync(params string[] UpdateColumns) { - Check.Exception(UpdateColumns == null, "UpdateColumns is null"); + if (UpdateColumns == null) { throw new SqlSugarException("UpdateColumns is null"); } if (_WhereColumnList != null && _WhereColumnList.Count != 0) { return await _Context.Fastest().AS(_AsName).BulkUpdateAsync(UpdateList.Select(it => it.Item).ToList(), _WhereColumnList.Select(it => it.DbColumnName).ToArray(), UpdateColumns).ConfigureAwait(false); @@ -182,7 +192,7 @@ namespace ThingsGateway.SqlSugar else { var pkColumns = this._Context.EntityMaintenance.GetEntityInfo().Columns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName).ToArray(); - Check.Exception(pkColumns.Length == 0, "need primary key"); + if (pkColumns.Length == 0) { throw new SqlSugarException("need primary key"); } return await _Context.Fastest().AS(_AsName).BulkUpdateAsync(UpdateList.Select(it => it.Item).ToList(), pkColumns, UpdateColumns).ConfigureAwait(false); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/DynamicLinq/SqlSugarDynamicExpressionParser.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/DynamicLinq/SqlSugarDynamicExpressionParser.cs index 2b5037da4..1cb4d6f8b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/DynamicLinq/SqlSugarDynamicExpressionParser.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/DynamicLinq/SqlSugarDynamicExpressionParser.cs @@ -9,7 +9,7 @@ namespace ThingsGateway.SqlSugar { if (StaticConfig.DynamicExpressionParserType == null) { - Check.ExceptionEasy("Please at program startup assignment: StaticConfig DynamicExpressionParserType = typeof (DynamicExpressionParser); NUGET is required to install Dynamic.Core", "请在程序启动时赋值: StaticConfig.DynamicExpressionParserType = typeof(DynamicExpressionParser); 需要NUGET安装 Dynamic.Core"); + Check.ExceptionLang("Please at program startup assignment: StaticConfig DynamicExpressionParserType = typeof (DynamicExpressionParser); NUGET is required to install Dynamic.Core", "请在程序启动时赋值: StaticConfig.DynamicExpressionParserType = typeof(DynamicExpressionParser); 需要NUGET安装 Dynamic.Core"); } if (StaticConfig.DynamicExpressionParsingConfig != null) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonSqlFuncToParameters.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonSqlFuncToParameters.cs index 6fbbefa15..d1ffb9298 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonSqlFuncToParameters.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonSqlFuncToParameters.cs @@ -31,8 +31,7 @@ namespace ThingsGateway.SqlSugar #region Level1 private static List GetObjectErrorParameters(JToken parameters) { - Check.Exception(true, ErrorMessage.GetThrowMessage($" {parameters.ToString()} format is error ", $" {parameters.ToString()} 格式错误")); - return null; + { throw new SqlSugarException(ErrorMessage.GetThrowMessage($" {parameters.ToString()} format is error ", $" {parameters.ToString()} 格式错误")); } } public List GetArrayParameters(JToken parameters) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonToJoinModels.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonToJoinModels.cs index e21f56078..b8092d58a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonToJoinModels.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/JsonToModel/JsonToJoinModels.cs @@ -11,7 +11,7 @@ namespace ThingsGateway.SqlSugar { JoinModel conditionalModels = new JoinModel(); var array = JArray.Parse(json); - Check.Exception(array.Count != 3, json + " format error"); + if (array.Count != 3) { throw new SqlSugarException(json + " format error"); } var tableName = array[0]; var shortName = array[1]; var onWhere = array[2]; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/FuncModelToSql.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/FuncModelToSql.cs index af4e3c411..706954e67 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/FuncModelToSql.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/FuncModelToSql.cs @@ -26,7 +26,7 @@ namespace ThingsGateway.SqlSugar { if (!(this.Context?.CurrentConnectionConfig?.MoreSettings?.EnableModelFuncMappingColumn == true)) { - Check.ExceptionEasy("Enable MappingColumn need in ConnectionConfig - > MoreSettings - > EnableModelFuncMappingColumn set to true", "MappingColumn考虑到风险情况需要开启才能使用,请在 ConnectionConfig->MoreSettings->EnableModelFuncMappingColumn设置为true"); + Check.ExceptionLang("Enable MappingColumn need in ConnectionConfig - > MoreSettings - > EnableModelFuncMappingColumn set to true", "MappingColumn考虑到风险情况需要开启才能使用,请在 ConnectionConfig->MoreSettings->EnableModelFuncMappingColumn设置为true"); } resSql = parameters[0] + ""; } @@ -71,7 +71,7 @@ namespace ThingsGateway.SqlSugar private static string GetMethodName(string name, List methods) { var result = methods.FirstOrDefault(it => name.EqualCase("SqlFunc_" + it) || name.EqualCase(it)); - Check.Exception(result == null, $" {name} is error "); + if (result == null) { throw new SqlSugarException($" {name} is error "); } return result; } private static List GetAllMethods(IDbMethods dbMethods) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/SqlPart.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/SqlPart.cs index 0678ffdbc..b144135ec 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/SqlPart.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/ModelToSql/SqlPart.cs @@ -10,7 +10,7 @@ namespace ThingsGateway.SqlSugar #region Root private string GetSqlPart(object value, List pars) { - Check.Exception(value == null, $" FieldName is error "); + if (value == null) { throw new SqlSugarException($" FieldName is error "); } if (IsSqlSplicingOperator(value)) { return GetSqlSplicingOperator(value); @@ -52,7 +52,7 @@ namespace ThingsGateway.SqlSugar } private static string GetSqlPartError(object value) { - Check.Exception(value == null, $" {value} is error "); + if (value == null) { throw new SqlSugarException($" {value} is error "); } return null; } private string GetSqlPartByObjectFuncModel(object value, List pars) @@ -71,7 +71,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(value == null, $" {value} is error "); + if (value == null) { throw new SqlSugarException($" {value} is error "); } return null; } } @@ -101,7 +101,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.ExceptionEasy($"{valueString} is error ", $"{valueString} 不是有效的拼接符号,拼接符号有:and、or、>=、<=、>、<、=、(、)"); + Check.ExceptionLang($"{valueString} is error ", $"{valueString} 不是有效的拼接符号,拼接符号有:and、or、>=、<=、>、<、=、(、)"); } return parvalue; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Common/JsonCommonProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Common/JsonCommonProvider.cs index 5279926e2..73a6a4b20 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Common/JsonCommonProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Common/JsonCommonProvider.cs @@ -62,7 +62,7 @@ namespace ThingsGateway.SqlSugar public KeyValuePair> GetWhere(JToken item, SqlSugarProvider context) { var value = item.First().ToString(); - Check.ExceptionEasy(item.First().Type != JTokenType.Array, "Where format error " + item, "Where格式错误" + item); + if (item.First().Type != JTokenType.Array) { throw new SqlSugarLangException("Where format error " + item, "Where格式错误" + item); } if (!IsConditionalModel(value)) { var obj = context.Utilities.JsonToSqlFuncModels(value); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Queryable/ResultHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Queryable/ResultHelper.cs index f08ee3864..0be11be87 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Queryable/ResultHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Queryable/ResultHelper.cs @@ -16,7 +16,7 @@ { AddDefaultSql(result); } - Check.ExceptionEasy(jsonQueryParameter.JoinNoSelect, "join query need Select", "联表查询需要设置Select"); + if (jsonQueryParameter.JoinNoSelect) { throw new SqlSugarLangException("join query need Select", "联表查询需要设置Select"); } return result; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhere.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhere.cs index 7fc32e4f0..ba8f71629 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhere.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhere.cs @@ -6,7 +6,7 @@ namespace ThingsGateway.SqlSugar { private void AppendWhere(JToken item) { - Check.Exception(isList, "Batch updates cannot use Where, only WhereColumns can set columns", "批量更新不能使用Where,只能通过WhereColumns设置列"); + if (isList) { throw new SqlSugarException("Batch updates cannot use Where, only WhereColumns can set columns"); } var sqlObj = jsonCommonProvider.GetWhere(item, sugarUpdateable.UpdateBuilder.Context); sugarUpdateable.Where(sqlObj.Key, sqlObj.Value); } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhereColumns.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhereColumns.cs index dcc5394c8..bc638f526 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhereColumns.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Provider/Updateable/AppendWhereColumns.cs @@ -7,7 +7,7 @@ namespace ThingsGateway.SqlSugar private void AppendWhereColumns(JToken item) { var columns = item.First().ToObject(); - Check.ExceptionEasy(columns.IsNullOrEmpty(), "need WhereColumns", "WhereColumns 需要设置列名"); + if (columns.IsNullOrEmpty()) { throw new SqlSugarLangException("need WhereColumns", "WhereColumns 需要设置列名"); } this.sugarUpdateable.WhereColumns(columns); } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Utils/Json2SqlConfig.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Utils/Json2SqlConfig.cs index 2a755aa3a..a639e02d4 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Utils/Json2SqlConfig.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Json2Sql/Utils/Json2SqlConfig.cs @@ -24,7 +24,7 @@ } internal static string GetWord(string key) { - Check.ExceptionEasy(words.ContainsKey(key) == false, $"{key} is error", $"{key} 不存在 "); + if (words.ContainsKey(key) == false) { throw new SqlSugarLangException($"{key} is error", $"{key} 不存在 "); } return words[key]; } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/CodeFirst/DmCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/CodeFirst/DmCodeFirst.cs index cb7c988b3..4e979a295 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/CodeFirst/DmCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/CodeFirst/DmCodeFirst.cs @@ -5,7 +5,7 @@ public override void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs index e9295aceb..0dcd8847e 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DbMaintenance/DmDbMaintenance.cs @@ -376,7 +376,7 @@ WHERE table_name = '" + tableName + "'"); CreateSchemaIfNotExists(this.Context); return true; } - Check.ExceptionEasy("dm no support create database ,only create schema", "达梦只支持创建Schema但不能创建数据库保证这个连接字符串数据库存在并能用。"); + Check.ExceptionLang("dm no support create database ,only create schema", "达梦只支持创建Schema但不能创建数据库保证这个连接字符串数据库存在并能用。"); return true; } public void CreateSchemaIfNotExists(ISqlSugarClient db) @@ -412,7 +412,7 @@ WHERE table_name = '" + tableName + "'"); { return true; } - Check.ExceptionEasy("dm no support create database ", "达梦不支持建库方法,请写有效连接字符串可以正常运行该方法。"); + Check.ExceptionLang("dm no support create database ", "达梦不支持建库方法,请写有效连接字符串可以正常运行该方法。"); return true; } public override bool AddRemark(EntityInfo entity) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DmProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DmProvider.cs index 6758af47e..a601059b7 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DmProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/DmProvider.cs @@ -69,7 +69,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } return base._DbConnection; @@ -246,7 +246,7 @@ namespace ThingsGateway.SqlSugar } if (it.Message?.Contains("Detail redacted as it may contain sensitive data.") == true) { - Check.ExceptionEasy(it.Message, $"错误:可能是字段太小超出,详细错误:{it.Message} "); + Check.ExceptionLang(it.Message, $"错误:可能是字段太小超出,详细错误:{it.Message} "); } }; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmBlukCopy.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmBlukCopy.cs index d4abc07d2..cc2651528 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmBlukCopy.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmBlukCopy.cs @@ -35,13 +35,13 @@ namespace ThingsGateway.SqlSugar return DbColumnInfoList.Count; } - public async Task ExecuteBulkCopyAsync() + public Task ExecuteBulkCopyAsync() { - if (DbColumnInfoList == null || DbColumnInfoList.Count == 0) return 0; + if (DbColumnInfoList == null || DbColumnInfoList.Count == 0) return Task.FromResult(0); if (Inserts[0].GetType() == typeof(DataTable)) { - return WriteToServer(); + return Task.FromResult(WriteToServer()); } DataTable dt = GetCopyData(); DmBulkCopy bulkCopy = GetBulkCopyInstance(); @@ -49,7 +49,6 @@ namespace ThingsGateway.SqlSugar try { bulkCopy.WriteToServer(dt); - await Task.Delay(0).ConfigureAwait(false); } catch (Exception) { @@ -57,7 +56,7 @@ namespace ThingsGateway.SqlSugar throw; } CloseDb(); - return DbColumnInfoList.Count; + return Task.FromResult(DbColumnInfoList.Count); } private int WriteToServer() @@ -65,7 +64,7 @@ namespace ThingsGateway.SqlSugar var dt = this.Inserts[0] as DataTable; if (dt == null) return 0; - Check.Exception(dt.TableName == "Table", "dt.TableName can't be null "); + if (dt.TableName == "Table") { throw new SqlSugarException("dt.TableName can't be null "); } dt = GetCopyWriteDataTable(dt); DmBulkCopy copy = GetBulkCopyInstance(); copy.DestinationTableName = this.Builder.GetTranslationColumnName(dt.TableName); @@ -125,7 +124,7 @@ namespace ThingsGateway.SqlSugar { if (value.Value != null && value.Value.ToString() == DateTime.MinValue.ToString()) { - value.Value = Convert.ToDateTime("1753/01/01"); + value.Value = UtilMethods.ToDate("1753-01-01"); } } if (value.Value == null) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmFastBuilder.cs index 71b2c83a3..1542e6525 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Dm/SqlBuilder/DmFastBuilder.cs @@ -56,14 +56,14 @@ namespace ThingsGateway.SqlSugar } public override string UpdateSql { get; set; } = @"UPDATE {1} TM INNER JOIN {2} TE ON {3} SET {0} "; - private async Task _Execute(DataTable dt) + private Task _Execute(DataTable dt) { DmBulkCopy bulkCopy = GetBulkCopyInstance(); bulkCopy.DestinationTableName = dt.TableName; try { bulkCopy.WriteToServer(dt); - await Task.Delay(0).ConfigureAwait(false);//No Support Async + } catch (Exception) { @@ -71,7 +71,7 @@ namespace ThingsGateway.SqlSugar throw; } CloseDb(); - return dt.Rows.Count; + return Task.FromResult(dt.Rows.Count); } public DmBulkCopy GetBulkCopyInstance() diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/CodeFirst/KdbndpCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/CodeFirst/KdbndpCodeFirst.cs index eb36ff2ce..ea8a1bf8e 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/CodeFirst/KdbndpCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/CodeFirst/KdbndpCodeFirst.cs @@ -5,7 +5,7 @@ public override void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/DbMaintenance/KdbndpDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/DbMaintenance/KdbndpDbMaintenance.cs index 2a3468fc0..b014c1bc4 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/DbMaintenance/KdbndpDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/DbMaintenance/KdbndpDbMaintenance.cs @@ -573,7 +573,7 @@ WHERE tgrelid = '" + tableName + "'::regclass"); protected override string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } foreach (var item in columns) { string columnName = item.DbColumnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/Insertable/KdbndpInserttable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/Insertable/KdbndpInserttable.cs index dd30cb592..beae145c9 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/Insertable/KdbndpInserttable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/Insertable/KdbndpInserttable.cs @@ -68,7 +68,7 @@ var identityKeys = GetIdentityKeys(); if (identityKeys.Count == 0) { return this.ExecuteCommand() > 0; } var idValue = ExecuteReturnBigIdentity(); - Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); + if (identityKeys.Count > 1) { throw new SqlSugarException("ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); } var identityKey = identityKeys[0]; object setValue = 0; if (idValue > int.MaxValue) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/KdbndpSQLProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/KdbndpSQLProvider.cs index 699f10b1b..f9eb2188d 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/KdbndpSQLProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/KdbndpSQLProvider.cs @@ -23,7 +23,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } return base._DbConnection; @@ -43,7 +43,7 @@ namespace ThingsGateway.SqlSugar { if (ex.Message.Contains("Version string portion was too short or too long")) { - Check.Exception(true, "人大金仓R6请安装 Nuget:SqlSugarCore.Kdbndp到最新版本"); + { throw new SqlSugarException("人大金仓R6请安装 Nuget:SqlSugarCore.Kdbndp到最新版本"); } } throw; } @@ -124,7 +124,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, sqlParameter.Value.GetType().Name + " No Support"); + { throw new SqlSugarException(sqlParameter.Value.GetType().Name + " No Support"); } } } if (sqlParameter.Direction == 0) @@ -164,7 +164,7 @@ namespace ThingsGateway.SqlSugar } if (it.Message?.StartsWith("42883: function uuid_generate_v4() does not exist") == true) { - Check.ExceptionEasy(it.Message, $"使用uuid_generate_v4()函数需要创建 CREATE EXTENSION IF NOT EXISTS kbcrypto;CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\" "); + Check.ExceptionLang(it.Message, $"使用uuid_generate_v4()函数需要创建 CREATE EXTENSION IF NOT EXISTS kbcrypto;CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\" "); } }; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpBuilder.cs index 9574850e1..c926519df 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpBuilder.cs @@ -48,8 +48,8 @@ //} public override string GetTranslationColumnName(string entityName, string propertyName) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); - Check.ArgumentNullException(propertyName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } + if (propertyName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } var context = this.Context; var mappingInfo = context .MappingColumns @@ -61,7 +61,7 @@ public override string GetTranslationTableName(string name) { - Check.ArgumentNullException(name, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (name == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } var context = this.Context; var mappingInfo = context diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpExpressionContext.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpExpressionContext.cs index 20c7c695c..a4c9de013 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpExpressionContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpExpressionContext.cs @@ -28,7 +28,7 @@ public override string GetTranslationTableName(string entityName, bool isMapping = true) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } if (IsTranslationText(entityName)) return entityName; isMapping = isMapping && this.MappingTables.HasValue(); var isComplex = entityName.Contains(UtilConstants.Dot); @@ -66,7 +66,7 @@ } public override string GetTranslationColumnName(string columnName) { - Check.ArgumentNullException(columnName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (columnName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) { return columnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpFastBuilder.cs index 11bef188f..28e09a0e0 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpFastBuilder.cs @@ -17,8 +17,8 @@ namespace ThingsGateway.SqlSugar //public virtual async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) //{ - // Check.ArgumentNullException(!updateColumns.Any(), "update columns count is 0"); - // Check.ArgumentNullException(!whereColumns.Any(), "where columns count is 0"); + // if(!updateColumns.Any() ==null){throw new SqlSugarException("update columns count is 0");} + // if(!whereColumns.Any() ==null){throw new SqlSugarException("where columns count is 0");} // var sets = string.Join(",", updateColumns.Select(it => $"TM.{it}=TE.{it}")); // var wheres = string.Join(",", whereColumns.Select(it => $"TM.{it}=TE.{it}")); // string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); @@ -114,8 +114,8 @@ namespace ThingsGateway.SqlSugar public override async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) { var sqlquerybulder = this.Context.Queryable().SqlBuilder; - Check.ArgumentNullException(updateColumns.Length == 0, "update columns count is 0"); - Check.ArgumentNullException(whereColumns.Length == 0, "where columns count is 0"); + if (updateColumns.Length == 0) { throw new SqlSugarException("update columns count is 0"); } + if (whereColumns.Length == 0) { throw new SqlSugarException("where columns count is 0"); } var sets = string.Join(",", updateColumns.Select(it => $"{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); var wheres = string.Join(" AND ", whereColumns.Select(it => $"{tableName}.{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpUpdateBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpUpdateBuilder.cs index 9d71b6f3b..fc63d3771 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpUpdateBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Kdbndp/SqlBuilder/KdbndpUpdateBuilder.cs @@ -43,9 +43,9 @@ namespace ThingsGateway.SqlSugar if (type == UtilConstants.DateType) { var date = value.ObjToDate(); - if (date < Convert.ToDateTime("1900-1-1")) + if (date < UtilMethods.MinDate) { - date = Convert.ToDateTime("1900-1-1"); + date = UtilMethods.MinDate; } return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"; } @@ -87,7 +87,7 @@ namespace ThingsGateway.SqlSugar protected override string TomultipleSqlString(List> groupList) { - Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + if (PrimaryKeys == null || PrimaryKeys.Count == 0) { throw new SqlSugarException(" Update List need Primary key"); } int pageSize = 200; int pageIndex = 1; int totalRecord = groupList.Count; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/CodeFirst/MySqlCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/CodeFirst/MySqlCodeFirst.cs index 303f0a8f2..69ea4201a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/CodeFirst/MySqlCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/CodeFirst/MySqlCodeFirst.cs @@ -5,7 +5,7 @@ public override void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/DorisHelper.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/DorisHelper.cs index 2ab25937a..9278c90a8 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/DorisHelper.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/DorisHelper.cs @@ -41,8 +41,8 @@ var pk = columns.FirstOrDefault(it => it.IsPrimarykey); if (pk != null) { - Check.ExceptionEasy(columns.Where(it => it.IsIdentity).Count() > 1, "Doris identity key no supported", "Doris不支持自增"); - Check.ExceptionEasy(columns.Where(it => it.IsPrimarykey).Count() > 1, "Doris Only one primary key is supported", "Doris只支持单主键"); + if (columns.Where(it => it.IsIdentity).Count() > 1) { throw new SqlSugarLangException("Doris identity key no supported", "Doris不支持自增"); } + if (columns.Where(it => it.IsPrimarykey).Count() > 1) { throw new SqlSugarLangException("Doris Only one primary key is supported", "Doris只支持单主键"); } sql = sql.Replace("$PrimaryKey)", ")"); var pkName = sqlBuilder.GetTranslationColumnName(pk.DbColumnName); sql += " \r\nENGINE=OLAP\r\nUNIQUE KEY(" + pkName + ")\r\nDISTRIBUTED BY HASH(" + pkName + ") BUCKETS 1\r\nPROPERTIES (\r\n 'replication_num' = '1',\r\n 'storage_format' = 'DEFAULT'\r\n);\r\n\r\n"; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/MySqlDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/MySqlDbMaintenance.cs index f7cd35722..58f1e2612 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/MySqlDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/DbMaintenance/MySqlDbMaintenance.cs @@ -348,7 +348,7 @@ WHERE EVENT_OBJECT_TABLE = '" + tableName + "'"); { if (SugarCompatible.IsFramework && ex.Message == "Invalid attempt to Read when reader is closed.") { - Check.ExceptionEasy($"To upgrade the MySql.Data. Error:{ex.Message}", $" 请先升级MySql.Data 。 详细错误:{ex.Message}"); + Check.ExceptionLang($"To upgrade the MySql.Data. Error:{ex.Message}", $" 请先升级MySql.Data 。 详细错误:{ex.Message}"); return true; } else @@ -389,7 +389,7 @@ WHERE EVENT_OBJECT_TABLE = '" + tableName + "'"); // DataType = ""VARCHAR(30) NOT NULL COMMENT 'xxxxx'"", // DbColumnName = ""columnname"" //}})" ; - //Check.Exception(true,"MySql no support AddColumnRemark , use " + message); + //{throw new SqlSugarException("MySql no support AddColumnRemark , use " + message);} return true; } /// @@ -423,7 +423,7 @@ WHERE EVENT_OBJECT_TABLE = '" + tableName + "'"); } else { - Check.ExceptionEasy("Failed to create the database. The database name has a keyword. Please change the name", "建库失败,库名存在关键字,请换一个名字"); + Check.ExceptionLang("Failed to create the database. The database name has a keyword. Please change the name", "建库失败,库名存在关键字,请换一个名字"); } } else @@ -526,7 +526,7 @@ WHERE EVENT_OBJECT_TABLE = '" + tableName + "'"); protected override string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } foreach (var item in columns) { ConvertCreateColumnInfo(item); @@ -727,7 +727,7 @@ WHERE EVENT_OBJECT_TABLE = '" + tableName + "'"); } catch (Exception) { - Check.ExceptionEasy("Need MySqlBackup.NET.MySqlConnector", "需要安装:MySqlBackup.NET.MySqlConnector"); + Check.ExceptionLang("Need MySqlBackup.NET.MySqlConnector", "需要安装:MySqlBackup.NET.MySqlConnector"); throw; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/MySqlProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/MySqlProvider.cs index 8a0814ae0..c6366cce8 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/MySqlProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/MySqlProvider.cs @@ -22,7 +22,7 @@ namespace ThingsGateway.SqlSugar try { var mySqlConnectionString = base.Context.CurrentConnectionConfig.ConnectionString; - Check.ExceptionEasy(String.IsNullOrEmpty(mySqlConnectionString), "ConnectionString is not null", "连接字符串ConnectionString不能为Null"); + if (String.IsNullOrEmpty(mySqlConnectionString)) { throw new SqlSugarLangException("ConnectionString is not null", "连接字符串ConnectionString不能为Null"); } if (!mySqlConnectionString.Contains("charset", StringComparison.CurrentCultureIgnoreCase) && !mySqlConnectionString.Contains("character", StringComparison.CurrentCultureIgnoreCase)) { mySqlConnectionString = mySqlConnectionString.Trim().TrimEnd(';') + ";charset=utf8;"; @@ -41,7 +41,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } } @@ -164,7 +164,7 @@ namespace ThingsGateway.SqlSugar if (ex is NullReferenceException && SugarCompatible.IsFramework) { - Check.ExceptionEasy($"To upgrade the MySql.Data. Error:{ex.Message}", $" 请先升级MySql.Data 。 详细错误:{ex.Message}"); + Check.ExceptionLang($"To upgrade the MySql.Data. Error:{ex.Message}", $" 请先升级MySql.Data 。 详细错误:{ex.Message}"); } } @@ -191,7 +191,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ex.Message); + { throw new SqlSugarException(ex.Message); } } } return sqlCommand; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlFastBuilder.cs index 9e9cc234e..35b1e4773 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlFastBuilder.cs @@ -61,16 +61,16 @@ namespace ThingsGateway.SqlSugar { if (ex.Message == "The used command is not allowed with this MySQL version") { - Check.ExceptionEasy("connection string add : AllowLoadLocalInfile=true", "BulkCopy MySql连接字符串需要添加 AllowLoadLocalInfile=true; 添加后如果还不行Mysql数据库执行一下 SET GLOBAL local_infile=1 "); + Check.ExceptionLang("connection string add : AllowLoadLocalInfile=true", "BulkCopy MySql连接字符串需要添加 AllowLoadLocalInfile=true; 添加后如果还不行Mysql数据库执行一下 SET GLOBAL local_infile=1 "); } else if (ex.Message.Contains("To use MySqlBulkLoader.Local=true, set Allo")) { - Check.ExceptionEasy("connection string add : AllowLoadLocalInfile=true", "BulkCopy MySql连接字符串需要添加 AllowLoadLocalInfile=true; 添加后如果还不行Mysql数据库执行一下 SET GLOBAL local_infile=1 "); + Check.ExceptionLang("connection string add : AllowLoadLocalInfile=true", "BulkCopy MySql连接字符串需要添加 AllowLoadLocalInfile=true; 添加后如果还不行Mysql数据库执行一下 SET GLOBAL local_infile=1 "); } else if (ex.Message == "Loading local data is disabled; this must be enabled on both the client and server sides") { await this.Context.Ado.ExecuteCommandAsync("SET GLOBAL local_infile=1").ConfigureAwait(false); - Check.ExceptionEasy(ex.Message, " 检测到你没有开启文件,AllowLoadLocalInfile=true加到自符串上,已自动执行 SET GLOBAL local_infile=1 在试一次"); + Check.ExceptionLang(ex.Message, " 检测到你没有开启文件,AllowLoadLocalInfile=true加到自符串上,已自动执行 SET GLOBAL local_infile=1 在试一次"); } else { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlUpdateBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlUpdateBuilder.cs index 68cacf9fe..4a6ca73f9 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlUpdateBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/MySql/SqlBuilder/MySqlUpdateBuilder.cs @@ -36,7 +36,7 @@ namespace ThingsGateway.SqlSugar } protected override string TomultipleSqlString(List> groupList) { - Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + if (PrimaryKeys == null || PrimaryKeys.Count == 0) { throw new SqlSugarException(" Update List need Primary key"); } int pageSize = 200; int pageIndex = 1; int totalRecord = groupList.Count; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/DbMaintenance/OracleDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/DbMaintenance/OracleDbMaintenance.cs index ee79bd1d8..f26df977d 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/DbMaintenance/OracleDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/DbMaintenance/OracleDbMaintenance.cs @@ -390,7 +390,7 @@ WHERE table_name = '" + tableName + "'"); { return true; } - Check.ExceptionEasy("Oracle no support create database ", "Oracle不支持建库方法,请写有效连接字符串可以正常运行该方法。"); + Check.ExceptionLang("Oracle no support create database ", "Oracle不支持建库方法,请写有效连接字符串可以正常运行该方法。"); return true; } public override bool CreateDatabase(string databaseName, string databaseDirectory = null) @@ -399,7 +399,7 @@ WHERE table_name = '" + tableName + "'"); { return true; } - Check.ExceptionEasy("Oracle no support create database ", "Oracle不支持建库方法,请写有效连接字符串可以正常运行该方法。"); + Check.ExceptionLang("Oracle no support create database ", "Oracle不支持建库方法,请写有效连接字符串可以正常运行该方法。"); return true; } public override bool AddRemark(EntityInfo entity) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/Insertable/OracleInsertable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/Insertable/OracleInsertable.cs index 898bb391e..cac16d357 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/Insertable/OracleInsertable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/Insertable/OracleInsertable.cs @@ -187,7 +187,7 @@ namespace ThingsGateway.SqlSugar InsertBuilder.OracleSeqInfoList = new Dictionary(); if ((identities.HasValue() && insertCount > 1) || InsertBuilder.IsBlukCopy) { - Check.Exception(identities.Count != identities.Distinct().Count(), "The field sequence needs to be unique"); + if (identities.Count != identities.Distinct().Count()) { throw new SqlSugarException("The field sequence needs to be unique"); } foreach (var seqName in identities) { int seqBeginValue = 0; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/OracleProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/OracleProvider.cs index e58206462..4815d0110 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/OracleProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/OracleProvider.cs @@ -66,7 +66,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } return base._DbConnection; } @@ -157,7 +157,7 @@ namespace ThingsGateway.SqlSugar } else if (Parameter.ParameterName.IsContainsInCase(KeyWord)) { - Check.ExceptionEasy($" {Parameter.ParameterName} is key word", $"{Parameter.ParameterName}是关键词"); + Check.ExceptionLang($" {Parameter.ParameterName} is key word", $"{Parameter.ParameterName}是关键词"); } } } @@ -191,7 +191,7 @@ namespace ThingsGateway.SqlSugar } if (it.Message?.Contains("无效的主机/绑定变量名") == true) { - Check.ExceptionEasy(it.Message, $"错误:{it.Message},出现这个错的原因: 1.可能是参数名为关键词(例如 @user )2. SQL错误。"); + Check.ExceptionLang(it.Message, $"错误:{it.Message},出现这个错的原因: 1.可能是参数名为关键词(例如 @user )2. SQL错误。"); } }; public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleBlukCopy.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleBlukCopy.cs index 0a36419de..0613385ad 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleBlukCopy.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleBlukCopy.cs @@ -94,7 +94,7 @@ namespace ThingsGateway.SqlSugar if (dt == null) return 0; - Check.Exception(dt.TableName == "Table", "dt.TableName can't be null "); + if (dt.TableName == "Table") { throw new SqlSugarException("dt.TableName can't be null "); } dt = GetCopyWriteDataTable(dt); @@ -197,7 +197,7 @@ namespace ThingsGateway.SqlSugar if (value.Value != null && value.Value.ToString() == DateTime.MinValue.ToString()) { - value.Value = Convert.ToDateTime("1900/01/01"); + value.Value = UtilMethods.MinDate; } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleFastBuilder.cs index a22896f79..b6b892d18 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oracle/SqlBuilder/OracleFastBuilder.cs @@ -39,8 +39,8 @@ namespace ThingsGateway.SqlSugar public override async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) { var sqlBuilder = this.Context.Queryable().SqlBuilder; - Check.ArgumentNullException(updateColumns.Length == 0, "update columns count is 0"); - Check.ArgumentNullException(whereColumns.Length == 0, "where columns count is 0"); + if (updateColumns.Length == 0) { throw new SqlSugarException("update columns count is 0"); } + if (whereColumns.Length == 0) { throw new SqlSugarException("where columns count is 0"); } var sets = string.Join(",", updateColumns.Select(it => $"TM{it}=TE{it}")); var wheres = string.Join(" AND ", whereColumns.Select(it => $"TM.{sqlBuilder.GetTranslationColumnName(it)}=TE.{sqlBuilder.GetTranslationColumnName(it)}")); var forms = string.Join(",", updateColumns.Select(it => $" TM.{sqlBuilder.GetTranslationColumnName(it)} TM{it},TE.{sqlBuilder.GetTranslationColumnName(it)} TE{it}")); @@ -70,7 +70,7 @@ namespace ThingsGateway.SqlSugar public override Task Merge(string tableName, DataTable dt, EntityInfo entityInfo, string[] whereColumns, string[] updateColumns, IEnumerable datas) where T : class { - Check.Exception(this.entityInfo.Columns.Any(it => it.OracleSequenceName.HasValue()), "The BulkMerge method cannot be used for sequence", "BulkMerge方法不能用序列"); + if (this.entityInfo.Columns.Any(it => it.OracleSequenceName.HasValue())) { throw new SqlSugarException("The BulkMerge method cannot be used for sequence"); } var sqlBuilder = this.Context.Queryable().SqlBuilder; var insertColumns = entityInfo.Columns .Where(it => it.IsIgnore == false && it.IsIdentity == false && it.InsertServerTime == false && it.InsertSql == null && it.OracleSequenceName == null && it.IsOnlyIgnoreInsert == false); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/CodeFirst/OscarCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/CodeFirst/OscarCodeFirst.cs index 674e20ee8..eab866863 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/CodeFirst/OscarCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/CodeFirst/OscarCodeFirst.cs @@ -5,7 +5,7 @@ public override void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/DbMaintenance/OscarDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/DbMaintenance/OscarDbMaintenance.cs index 8dfeeaba1..e47752d92 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/DbMaintenance/OscarDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/DbMaintenance/OscarDbMaintenance.cs @@ -338,7 +338,7 @@ namespace ThingsGateway.SqlSugar protected override string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } foreach (var item in columns) { string columnName = item.DbColumnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/Insertable/OscarInserttable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/Insertable/OscarInserttable.cs index 4af14acf3..db35c10f7 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/Insertable/OscarInserttable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/Insertable/OscarInserttable.cs @@ -52,7 +52,7 @@ var identityKeys = GetIdentityKeys(); if (identityKeys.Count == 0) { return this.ExecuteCommand() > 0; } var idValue = ExecuteReturnBigIdentity(); - Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); + if (identityKeys.Count > 1) { throw new SqlSugarException("ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); } var identityKey = identityKeys[0]; object setValue = 0; if (idValue > int.MaxValue) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/OscarProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/OscarProvider.cs index ec10c67f9..d27a9e0c1 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/OscarProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/OscarProvider.cs @@ -20,7 +20,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } return base._DbConnection; @@ -104,7 +104,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, sqlParameter.Value.GetType().Name + " No Support"); + { throw new SqlSugarException(sqlParameter.Value.GetType().Name + " No Support"); } } } if (sqlParameter.Direction == 0) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarBuilder.cs index c746aed55..10bfd57af 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarBuilder.cs @@ -56,8 +56,8 @@ //} public override string GetTranslationColumnName(string entityName, string propertyName) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); - Check.ArgumentNullException(propertyName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } + if (propertyName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } var context = this.Context; var mappingInfo = context .MappingColumns @@ -69,7 +69,7 @@ public override string GetTranslationTableName(string name) { - Check.ArgumentNullException(name, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (name == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } var context = this.Context; var mappingInfo = context diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarExpressionContext.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarExpressionContext.cs index 6b662e129..6f9d6c3c6 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarExpressionContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarExpressionContext.cs @@ -36,7 +36,7 @@ public override string GetTranslationTableName(string entityName, bool isMapping = true) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } if (IsTranslationText(entityName)) return entityName; isMapping = isMapping && this.MappingTables.HasValue(); var isComplex = entityName.Contains(UtilConstants.Dot); @@ -74,7 +74,7 @@ } public override string GetTranslationColumnName(string columnName) { - Check.ArgumentNullException(columnName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (columnName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) { return columnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarUpdateBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarUpdateBuilder.cs index cf745d715..b2281a31b 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarUpdateBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Oscar/SqlBuilder/OscarUpdateBuilder.cs @@ -43,9 +43,9 @@ namespace ThingsGateway.SqlSugar if (type == UtilConstants.DateType) { var date = value.ObjToDate(); - if (date < Convert.ToDateTime("1900-1-1")) + if (date < UtilMethods.MinDate) { - date = Convert.ToDateTime("1900-1-1"); + date = UtilMethods.MinDate; } return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/CodeFirst/PostgreSQLCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/CodeFirst/PostgreSQLCodeFirst.cs index f16dc41f2..5851ea188 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/CodeFirst/PostgreSQLCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/CodeFirst/PostgreSQLCodeFirst.cs @@ -15,7 +15,7 @@ public override void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/DbMaintenance/PostgreSQLDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/DbMaintenance/PostgreSQLDbMaintenance.cs index 154d1eee2..f1e0797e1 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/DbMaintenance/PostgreSQLDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/DbMaintenance/PostgreSQLDbMaintenance.cs @@ -479,7 +479,7 @@ WHERE tgrelid = '" + tableName + "'::regclass"); protected override string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } var identityStrategy = this.Context.CurrentConnectionConfig.MoreSettings?.PostgresIdentityStrategy; foreach (var item in columns) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/Insertable/PostgreSQLInserttable.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/Insertable/PostgreSQLInserttable.cs index 209c0fa4d..6f886f99d 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/Insertable/PostgreSQLInserttable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/Insertable/PostgreSQLInserttable.cs @@ -71,7 +71,7 @@ var identityKeys = GetIdentityKeys(); if (identityKeys.Count == 0) { return this.ExecuteCommand() > 0; } var idValue = ExecuteReturnBigIdentity(); - Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); + if (identityKeys.Count > 1) { throw new SqlSugarException("ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); } var identityKey = identityKeys[0]; object setValue = 0; if (idValue > int.MaxValue) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/PostgreSQLProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/PostgreSQLProvider.cs index 07362c522..88ba40cbc 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/PostgreSQLProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/PostgreSQLProvider.cs @@ -30,7 +30,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } return base._DbConnection; @@ -172,7 +172,7 @@ namespace ThingsGateway.SqlSugar } else { - Check.Exception(true, sqlParameter.Value.GetType().Name + " No Support"); + { throw new SqlSugarException(sqlParameter.Value.GetType().Name + " No Support"); } } } @@ -234,7 +234,7 @@ namespace ThingsGateway.SqlSugar } if (it.Message?.StartsWith("42883: function uuid_generate_v4() does not exist") == true) { - Check.ExceptionEasy(it.Message, $"使用uuid_generate_v4()函数需要创建 CREATE EXTENSION IF NOT EXISTS pgcrypto;CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\" "); + Check.ExceptionLang(it.Message, $"使用uuid_generate_v4()函数需要创建 CREATE EXTENSION IF NOT EXISTS pgcrypto;CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\" "); } }; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLBuilder.cs index 68c539f49..30eb1716c 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLBuilder.cs @@ -57,8 +57,8 @@ //} public override string GetTranslationColumnName(string entityName, string propertyName) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); - Check.ArgumentNullException(propertyName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } + if (propertyName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } var context = this.Context; var mappingInfo = context .MappingColumns @@ -70,7 +70,7 @@ public override string GetTranslationTableName(string name) { - Check.ArgumentNullException(name, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (name == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } var context = this.Context; var mappingInfo = context diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLExpressionContext.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLExpressionContext.cs index f16058063..824b25b96 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLExpressionContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLExpressionContext.cs @@ -34,7 +34,7 @@ } public override string GetTranslationTableName(string entityName, bool isMapping = true) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } if (IsTranslationText(entityName)) return entityName; isMapping = isMapping && this.MappingTables.HasValue(); var isComplex = entityName.Contains(UtilConstants.Dot); @@ -72,7 +72,7 @@ } public override string GetTranslationColumnName(string columnName) { - Check.ArgumentNullException(columnName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (columnName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) { return columnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLFastBuilder.cs index d71c02b6d..79993483f 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLFastBuilder.cs @@ -21,8 +21,8 @@ namespace ThingsGateway.SqlSugar //public virtual async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) //{ - // Check.ArgumentNullException(!updateColumns.Any(), "update columns count is 0"); - // Check.ArgumentNullException(!whereColumns.Any(), "where columns count is 0"); + // if(!updateColumns.Any() ==null){throw new SqlSugarException("update columns count is 0");} + // if(!whereColumns.Any() ==null){throw new SqlSugarException("where columns count is 0");} // var sets = string.Join(",", updateColumns.Select(it => $"TM.{it}=TE.{it}")); // var wheres = string.Join(",", whereColumns.Select(it => $"TM.{it}=TE.{it}")); // string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); @@ -145,8 +145,8 @@ namespace ThingsGateway.SqlSugar public override async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) { var sqlquerybulder = this.Context.Queryable().SqlBuilder; - Check.ArgumentNullException(updateColumns.Length == 0, "update columns count is 0"); - Check.ArgumentNullException(whereColumns.Length == 0, "where columns count is 0"); + if (updateColumns.Length == 0) { throw new SqlSugarException("update columns count is 0"); } + if (whereColumns.Length == 0) { throw new SqlSugarException("where columns count is 0"); } var sets = string.Join(",", updateColumns.Select(it => $"{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); var wheres = string.Join(" AND ", whereColumns.Select(it => $"{tableName}.{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLUpdateBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLUpdateBuilder.cs index 8144c17b7..c040336e1 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLUpdateBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/PostgreSQL/SqlBuilder/PostgreSQLUpdateBuilder.cs @@ -101,7 +101,7 @@ namespace ThingsGateway.SqlSugar protected override string TomultipleSqlString(List> groupList) { - Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + if (PrimaryKeys == null || PrimaryKeys.Count == 0) { throw new SqlSugarException(" Update List need Primary key"); } int pageSize = 200; int pageIndex = 1; int totalRecord = groupList.Count; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/CodeFirst/QuestDBCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/CodeFirst/QuestDBCodeFirst.cs index 45c58119e..296f6b010 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/CodeFirst/QuestDBCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/CodeFirst/QuestDBCodeFirst.cs @@ -17,7 +17,7 @@ namespace ThingsGateway.SqlSugar public override void NoExistLogic(EntityInfo entityInfo) { var tableName = GetTableName(entityInfo); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/DbMaintenance/QuestDBDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/DbMaintenance/QuestDBDbMaintenance.cs index cca0737bd..5d9da79ac 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/DbMaintenance/QuestDBDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/DbMaintenance/QuestDBDbMaintenance.cs @@ -239,7 +239,7 @@ namespace ThingsGateway.SqlSugar { if (!columnInfo.Type.EqualCase("SYMBOL")) { - Check.ExceptionEasy(true, "Only the SYMBOL type can be indexed", $"字段{columnInfo.Column} 不是SYMBOL并且实体是string才能添加索引,CodeFirst需要指定类型: SYMBOL"); + if (true) { throw new SqlSugarLangException("Only the SYMBOL type can be indexed", $"字段{columnInfo.Column} 不是SYMBOL并且实体是string才能添加索引,CodeFirst需要指定类型: SYMBOL"); } } if (columnInfo.Indexed == false) { @@ -403,7 +403,7 @@ namespace ThingsGateway.SqlSugar protected override string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } foreach (var item in columns) { string columnName = item.DbColumnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/QuestDBProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/QuestDBProvider.cs index ff61d16d0..90a4bdce6 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/QuestDBProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/QuestDBProvider.cs @@ -23,7 +23,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } return base._DbConnection; @@ -99,7 +99,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } this.CheckConnectionAfter(this.Connection); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBBuilder.cs index 1f83f0953..1688f5c68 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBBuilder.cs @@ -68,8 +68,8 @@ //} public override string GetTranslationColumnName(string entityName, string propertyName) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); - Check.ArgumentNullException(propertyName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } + if (propertyName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } var context = this.Context; var mappingInfo = context .MappingColumns @@ -81,7 +81,7 @@ public override string GetTranslationTableName(string name) { - Check.ArgumentNullException(name, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (name == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } var context = this.Context; var mappingInfo = context diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBExpressionContext.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBExpressionContext.cs index 622af38a4..c7ea2a312 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBExpressionContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBExpressionContext.cs @@ -34,7 +34,7 @@ } public override string GetTranslationTableName(string entityName, bool isMapping = true) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } if (IsTranslationText(entityName)) return entityName; isMapping = isMapping && this.MappingTables.HasValue(); var isComplex = entityName.Contains(UtilConstants.Dot); @@ -72,7 +72,7 @@ } public override string GetTranslationColumnName(string columnName) { - Check.ArgumentNullException(columnName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (columnName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) { return columnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBFastBuilder.cs index 85f60e208..8529e09f9 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/QuestDB/SqlBuilder/QuestDBFastBuilder.cs @@ -21,8 +21,8 @@ namespace ThingsGateway.SqlSugar //public virtual async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) //{ - // Check.ArgumentNullException(!updateColumns.Any(), "update columns count is 0"); - // Check.ArgumentNullException(!whereColumns.Any(), "where columns count is 0"); + // if(!updateColumns.Any() ==null){throw new SqlSugarException("update columns count is 0");} + // if(!whereColumns.Any() ==null){throw new SqlSugarException("where columns count is 0");} // var sets = string.Join(",", updateColumns.Select(it => $"TM.{it}=TE.{it}")); // var wheres = string.Join(",", whereColumns.Select(it => $"TM.{it}=TE.{it}")); // string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); @@ -93,8 +93,8 @@ namespace ThingsGateway.SqlSugar public override async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) { var sqlquerybulder = this.Context.Queryable().SqlBuilder; - Check.ArgumentNullException(updateColumns.Length == 0, "update columns count is 0"); - Check.ArgumentNullException(whereColumns.Length == 0, "where columns count is 0"); + if (updateColumns.Length == 0) { throw new SqlSugarException("update columns count is 0"); } + if (whereColumns.Length == 0) { throw new SqlSugarException("where columns count is 0"); } var sets = string.Join(",", updateColumns.Select(it => $"{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); var wheres = string.Join(" AND ", whereColumns.Select(it => $"{tableName}.{sqlquerybulder.GetTranslationColumnName(it)}=TE.{sqlquerybulder.GetTranslationColumnName(it)}")); string sql = string.Format(UpdateSql, sets, tableName, tempName, wheres); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/DbMaintenance/SqlServerDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/DbMaintenance/SqlServerDbMaintenance.cs index d08e3d7ab..ccce31d24 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/DbMaintenance/SqlServerDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/DbMaintenance/SqlServerDbMaintenance.cs @@ -649,7 +649,7 @@ AND syscomments.text LIKE '%" + tableName + "%'"); } else { - Check.ExceptionEasy("Failed to create the database. The database name has a keyword. Please change the name", "建库失败,库名存在关键字,请换一个名字"); + Check.ExceptionLang("Failed to create the database. The database name has a keyword. Please change the name", "建库失败,库名存在关键字,请换一个名字"); } } else diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerBlukCopy.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerBlukCopy.cs index 21e57a7d4..fb391ad96 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerBlukCopy.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerBlukCopy.cs @@ -65,7 +65,7 @@ namespace ThingsGateway.SqlSugar var dt = this.Inserts.First() as DataTable; if (dt == null) return 0; - Check.Exception(dt.TableName == "Table", "dt.TableName can't be null "); + if (dt.TableName == "Table") { throw new SqlSugarException("dt.TableName can't be null "); } dt = GetCopyWriteDataTable(dt); SqlBulkCopy copy = GetBulkCopyInstance(); copy.DestinationTableName = this.Builder.GetTranslationColumnName(dt.TableName); @@ -125,7 +125,7 @@ namespace ThingsGateway.SqlSugar { if (value.Value != null && value.Value.ToString() == DateTime.MinValue.ToString()) { - value.Value = Convert.ToDateTime("1753/01/01"); + value.Value = UtilMethods.ToDate("1753-01-01"); } } if (value.Value == null) diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerUpdateBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerUpdateBuilder.cs index 883af7224..69dcab781 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerUpdateBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlBuilder/SqlServerUpdateBuilder.cs @@ -7,7 +7,7 @@ namespace ThingsGateway.SqlSugar { protected override string TomultipleSqlString(List> groupList) { - Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List need Primary key"); + if (PrimaryKeys == null || PrimaryKeys.Count == 0) { throw new SqlSugarException(" Update List need Primary key"); } int pageSize = 200; int pageIndex = 1; int totalRecord = groupList.Count; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlServerProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlServerProvider.cs index bda6b0040..2b5c5c8d7 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlServerProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/SqlServer/SqlServerProvider.cs @@ -24,7 +24,7 @@ namespace ThingsGateway.SqlSugar } catch (Exception ex) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } return base._DbConnection; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/CodeFirst/SqliteCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/CodeFirst/SqliteCodeFirst.cs index 4b65b4895..fc5c7ec38 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/CodeFirst/SqliteCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/CodeFirst/SqliteCodeFirst.cs @@ -100,7 +100,7 @@ { if (item.IsPrimarykey || item.IsIdentity) { - Check.ExceptionEasy("Multiple primary keys cannot be modified", "多主键不能修改"); + Check.ExceptionLang("Multiple primary keys cannot be modified", "多主键不能修改"); } this.Context.DbMaintenance.AddColumn(tableName2, EntityColumnToDbColumn(entityInfo, tableName2, item)); } @@ -110,7 +110,7 @@ { var tableName = GetTableName(entityInfo); string backupName = tableName + DateTime.Now.ToString("yyyyMMddHHmmss"); - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Use Code First ,The primary key must not exceed 1");} List columns = new List(); if (entityInfo.Columns.HasValue()) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/DbMaintenance/SqliteDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/DbMaintenance/SqliteDbMaintenance.cs index 71e0fd109..c2823d9b2 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/DbMaintenance/SqliteDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/DbMaintenance/SqliteDbMaintenance.cs @@ -274,7 +274,7 @@ namespace ThingsGateway.SqlSugar { if (column.IsPrimarykey) { - Check.ExceptionEasy("Sqlite no support alter column primary key", "Sqlite不支持修改主键"); + Check.ExceptionLang("Sqlite no support alter column primary key", "Sqlite不支持修改主键"); } if (isTran) @@ -541,7 +541,7 @@ AND sql LIKE '%" + tableName + "%'"); //} if (item.IsIdentity && !item.IsPrimarykey) { - Check.Exception(true, "Identity only primary key"); + { throw new SqlSugarException("Identity only primary key"); } } } } @@ -567,7 +567,7 @@ AND sql LIKE '%" + tableName + "%'"); protected override string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } foreach (var item in columns) { string columnName = item.DbColumnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteFastBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteFastBuilder.cs index 83ae2c2a2..11937e931 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteFastBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteFastBuilder.cs @@ -11,8 +11,9 @@ namespace ThingsGateway.SqlSugar private bool IsUpdate = false; public string CharacterSet { get; set; } private DataTable UpdateDataTable { get; set; } + private Dictionary)> UpdateDataInfos { get; set; } public bool IsActionUpdateColumns { get; set; } - public DbFastestProperties DbFastestProperties { get; set; } = new DbFastestProperties() { IsNoCopyDataTable = true }; + public DbFastestProperties DbFastestProperties { get; set; } = new DbFastestProperties() { IsNoCopyDataTable = true, IsDataTable = false }; public SqliteFastBuilder(EntityInfo entityInfo) { this.entityInfo = entityInfo; @@ -28,12 +29,12 @@ namespace ThingsGateway.SqlSugar } } - public async Task CreateTempAsync(DataTable dt) where T : class, new() + public Task CreateTempAsync(DataTable dt) where T : class, new() { - await Task.Delay(0).ConfigureAwait(false); - IsUpdate = true; - } + IsUpdate = true; + return Task.CompletedTask; + } public async Task ExecuteBulkCopyAsync(DataTable dt) { if (dt.Rows.Count == 0 || IsUpdate) @@ -69,6 +70,44 @@ namespace ThingsGateway.SqlSugar return result; } + public async Task ExecuteBulkCopyAsync(string tableName, Dictionary)> list) + { + if (list.Count == 0 || IsUpdate) + { + this.UpdateDataInfos = list; + return 0; + } + foreach (var item in this.entityInfo.Columns) + { + if (item.IsIdentity) + { + list.Remove(item.DbColumnName); + } + } + int result = 0; + var cn = this.Context.Ado.Connection as SqliteConnection; + Open(cn); + if (this.Context.Ado.Transaction == null) + { +#pragma warning disable CA2007 // 考虑对等待的任务调用 ConfigureAwait + await using (var transaction = await cn.BeginTransactionAsync().ConfigureAwait(false)) + { + result = await _BulkCopy(tableName, list, result, cn).ConfigureAwait(false); + await transaction.CommitAsync().ConfigureAwait(false); + } +#pragma warning restore CA2007 // 考虑对等待的任务调用 ConfigureAwait + } + else + { + result = await _BulkCopy(tableName, list, result, cn).ConfigureAwait(false); + } + return result; + } + + + + + private async Task _BulkCopy(DataTable dt, List> dictionary, int i, SqliteConnection cn) { using (var cmd = cn.CreateCommand()) @@ -110,6 +149,67 @@ namespace ThingsGateway.SqlSugar } return i; } + + private async Task _BulkCopy(string tableName, Dictionary)> list, int i, SqliteConnection cn) + { + using (var cmd = cn.CreateCommand()) + { + if (this.Context?.CurrentConnectionConfig?.MoreSettings?.IsCorrectErrorSqlParameterName == true) + { + var count = list.FirstOrDefault().Value.Item2?.Count; + if (count > 0) + { + for (int index = 0; index < count; index++) + { + var row = list.GetRows(index).ToDictionary(a => a.ColumnName, a => a.Value); + cmd.CommandText = this.Context.InsertableT(row).AS(tableName).ToSqlString().Replace(";SELECT LAST_INSERT_ROWID();", ""); + TransformInsertCommand(cmd); + i += await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); + } + } + } + else + { + var count = list.FirstOrDefault().Value.Item2?.Count; + if (count > 0) + { + var row = list.GetRows(0).ToDictionary(a => a.ColumnName, a => a.Value); + cmd.CommandText = this.Context.InsertableT(row).AS(tableName).ToSql().Key.Replace(";SELECT LAST_INSERT_ROWID();", ""); + } + TransformInsertCommand(cmd); + if (count > 0) + { + for (int index = 0; index < count; index++) + { + var row = list.GetRows(index); + foreach (var item in row) + { + + if (IsBoolTrue(item)) + { + cmd.Parameters.AddWithValue("@" + item.ColumnName, true); + } + else if (IsBoolFalse(item)) + { + cmd.Parameters.AddWithValue("@" + item.ColumnName, false); + } + else + { + cmd.Parameters.AddWithValue("@" + item.ColumnName, item.Value); + } + } + + + i += await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); + cmd.Parameters.Clear(); + } + } + + } + } + return i; + } + private void TransformInsertCommand(SqliteCommand cmd) { if (this.DbFastestProperties?.IsIgnoreInsertError == true) @@ -168,17 +268,87 @@ namespace ThingsGateway.SqlSugar } return i; } + private async Task _BulkUpdate(string tableName, Dictionary)> list, int i, string[] whereColumns, string[] updateColumns, SqliteConnection cn) + { + using (var cmd = cn.CreateCommand()) + { + if (this.Context?.CurrentConnectionConfig?.MoreSettings?.IsCorrectErrorSqlParameterName == true) + { + var count = list.FirstOrDefault().Value.Item2?.Count; + if (count > 0) + { + for (int index = 0; index < count; index++) + { + var row = list.GetRows(index).ToDictionary(a => a.ColumnName, a => a.Value); + cmd.CommandText = this.Context.UpdateableT(row) + .WhereColumns(whereColumns) + .UpdateColumns(updateColumns) + .AS(tableName).ToSqlString(); + i += await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); + } + } + + } + else + { + var count = list.FirstOrDefault().Value.Item2?.Count; + if (count > 0) + { + var row = list.GetRows(0).ToDictionary(a => a.ColumnName, a => a.Value); + cmd.CommandText = this.Context.UpdateableT(row) + .WhereColumns(whereColumns) + .UpdateColumns(updateColumns) + .AS(tableName).ToSql().Key; + } + + if (count > 0) + { + for (int index = 0; index < count; index++) + { + var row = list.GetRows(index); + foreach (var item in row) + { + + if (IsBoolTrue(item)) + { + cmd.Parameters.AddWithValue("@" + item.ColumnName, true); + } + else if (IsBoolFalse(item)) + { + cmd.Parameters.AddWithValue("@" + item.ColumnName, false); + } + else + { + cmd.Parameters.AddWithValue("@" + item.ColumnName, item.Value); + } + } + + + i += await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); + cmd.Parameters.Clear(); + } + } + } + } + return i; + } private static bool IsBoolFalse(DataRow dataRow, DataColumn item) { return dataRow[item.ColumnName] != null && dataRow[item.ColumnName] is string && dataRow[item.ColumnName].ToString() == ("isSqliteCore_False"); } - + private static bool IsBoolFalse(DataInfos dataRow) + { + return dataRow.Value != null && dataRow.Value is string str && str == ("isSqliteCore_False"); + } private static bool IsBoolTrue(DataRow dataRow, DataColumn item) { return dataRow[item.ColumnName] != null && dataRow[item.ColumnName] is string && dataRow[item.ColumnName].ToString() == ("isSqliteCore_True"); } - + private static bool IsBoolTrue(DataInfos dataRow) + { + return dataRow.Value != null && dataRow.Value is string str && str == ("isSqliteCore_True"); + } private static void Open(SqliteConnection cn) { if (cn.State != ConnectionState.Open) @@ -188,29 +358,60 @@ namespace ThingsGateway.SqlSugar public async Task UpdateByTempAsync(string tableName, string tempName, string[] updateColumns, string[] whereColumns) { var dt = UpdateDataTable; - if (dt.Rows.Count == 0) - { - return 0; - } - var dictionary = this.Context.Utilities.DataTableToDictionaryList(dt.Rows.Cast().Take(1).CopyToDataTable()); - int result = 0; - var cn = this.Context.Ado.Connection as SqliteConnection; - Open(cn); - if (this.Context.Ado.Transaction == null) + if (dt != null) { + + if (dt.Rows.Count == 0) + { + return 0; + } + var dictionary = this.Context.Utilities.DataTableToDictionaryList(dt.Rows.Cast().Take(1).CopyToDataTable()); + int result = 0; + var cn = this.Context.Ado.Connection as SqliteConnection; + Open(cn); + if (this.Context.Ado.Transaction == null) + { #pragma warning disable CA2007 // 考虑对等待的任务调用 ConfigureAwait - await using (var transaction = await cn.BeginTransactionAsync().ConfigureAwait(false)) + await using (var transaction = await cn.BeginTransactionAsync().ConfigureAwait(false)) + { + result = await _BulkUpdate(dt, dictionary, result, whereColumns, updateColumns, cn).ConfigureAwait(false); + await transaction.CommitAsync().ConfigureAwait(false); + } +#pragma warning restore CA2007 // 考虑对等待的任务调用 ConfigureAwait + } + else { result = await _BulkUpdate(dt, dictionary, result, whereColumns, updateColumns, cn).ConfigureAwait(false); - await transaction.CommitAsync().ConfigureAwait(false); } -#pragma warning restore CA2007 // 考虑对等待的任务调用 ConfigureAwait + return result; } + else { - result = await _BulkUpdate(dt, dictionary, result, whereColumns, updateColumns, cn).ConfigureAwait(false); + + if (UpdateDataInfos.FirstOrDefault().Value.Item2 == null || UpdateDataInfos.FirstOrDefault().Value.Item2?.Count == 0) + { + return 0; + } + int result = 0; + var cn = this.Context.Ado.Connection as SqliteConnection; + Open(cn); + if (this.Context.Ado.Transaction == null) + { +#pragma warning disable CA2007 // 考虑对等待的任务调用 ConfigureAwait + await using (var transaction = await cn.BeginTransactionAsync().ConfigureAwait(false)) + { + result = await _BulkUpdate(tableName, UpdateDataInfos, result, whereColumns, updateColumns, cn).ConfigureAwait(false); + await transaction.CommitAsync().ConfigureAwait(false); + } +#pragma warning restore CA2007 // 考虑对等待的任务调用 ConfigureAwait + } + else + { + result = await _BulkUpdate(tableName, UpdateDataInfos, result, whereColumns, updateColumns, cn).ConfigureAwait(false); + } + return result; } - return result; } public async Task Merge(string tableName, DataTable dt, EntityInfo entityInfo, string[] whereColumns, string[] updateColumns, IEnumerable datas) where T : class, new() @@ -225,5 +426,18 @@ namespace ThingsGateway.SqlSugar }).ConfigureAwait(false); return result; } + + public async Task Merge(string tableName, IEnumerable list, EntityInfo entityInfo, string[] whereColumns, string[] updateColumns, IEnumerable datas) where T : class, new() + { + var result = 0; + await Context.Utilities.PageEachAsync(datas, 2000, async pageItems => + { + var x = await Context.Storageable(pageItems).AS(tableName).WhereColumns(whereColumns).ToStorageAsync().ConfigureAwait(false); + result += await x.BulkCopyAsync().ConfigureAwait(false); + result += await x.BulkUpdateAsync(updateColumns).ConfigureAwait(false); + return result; + }).ConfigureAwait(false); + return result; + } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteInsertBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteInsertBuilder.cs index 7ef6687f4..b2222ae1e 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteInsertBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqlBuilder/SqliteInsertBuilder.cs @@ -4,163 +4,124 @@ namespace ThingsGateway.SqlSugar { public class SqliteInsertBuilder : InsertBuilder { - public override string SqlTemplate - { - get - { - if (IsReturnIdentity) - { - return @"INSERT INTO {0} - ({1}) - VALUES - ({2}) ;SELECT LAST_INSERT_ROWID();"; - } - else - { - return @"INSERT INTO {0} - ({1}) - VALUES - ({2}) ;"; - } - } - } + private const string InsertPrefix = "INSERT INTO "; + private const string InsertIgnorePrefix = "INSERT OR IGNORE INTO "; + + public override string SqlTemplate => + IsReturnIdentity + ? @"INSERT INTO {0} ({1}) VALUES ({2});SELECT LAST_INSERT_ROWID();" + : @"INSERT INTO {0} ({1}) VALUES ({2});"; + + public override string SqlTemplateBatch => "INSERT INTO {0} ({1})"; - public override string SqlTemplateBatch - { - get - { - return "INSERT INTO {0} ({1})"; - } - } public override string ToSqlString() { + // 过滤掉 null 值 if (IsNoInsertNull) - { DbColumnInfoList = DbColumnInfoList.Where(it => it.Value != null).ToList(); - } + + // 按 TableId 分组 var groupList = DbColumnInfoList.GroupBy(it => it.TableId).ToList(); - var isSingle = groupList.Count == 1; - string columnsString = string.Join(",", groupList[0].Select(it => Builder.GetTranslationColumnName(it.DbColumnName))); - if (isSingle) + var firstGroup = groupList[0]; + + // 列名缓存 + var columnNames = string.Join(",", firstGroup.Select(it => Builder.GetTranslationColumnName(it.DbColumnName))); + + if (groupList.Count == 1) { - string columnParametersString = string.Join(",", this.DbColumnInfoList.Select(it => base.GetDbColumn(it, Builder.SqlParameterKeyWord + it.DbColumnName))); + // 单条插入 + var columnValues = string.Join(",", DbColumnInfoList.Select(it => + base.GetDbColumn(it, Builder.SqlParameterKeyWord + it.DbColumnName))); + ActionMinDate(); - return string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString); + return string.Format(SqlTemplate, GetTableNameString, columnNames, columnValues); } - else + + // 批量插入 + var sb = new StringBuilder(256 + groupList.Count * 64); + sb.Append(InsertPrefix).Append(GetTableNameString).Append(" (").Append(columnNames).Append(") VALUES"); + + var groupCount = groupList.Count; + int i = 0; + + foreach (var group in groupList) { - StringBuilder batchInsetrSql = new StringBuilder(); - batchInsetrSql.Append("INSERT INTO " + GetTableNameString + " "); - batchInsetrSql.Append('('); - batchInsetrSql.Append(columnsString); - batchInsetrSql.Append(") VALUES"); - string insertColumns = ""; - int i = 0; - foreach (var item in groupList) + sb.Append('('); + + int itemCount = 0; + foreach (var col in group) { - batchInsetrSql.Append('('); - insertColumns = string.Join(",", item.Select(it => base.GetDbColumn(it, FormatValue(i, it.DbColumnName, it.Value)))); - batchInsetrSql.Append(insertColumns); - if (groupList.Last() == item) - { - batchInsetrSql.Append(") "); - } - else - { - batchInsetrSql.Append("), "); - } - i++; + if (itemCount++ > 0) sb.Append(','); + sb.Append(base.GetDbColumn(col, FormatValue(i, col.DbColumnName, col.Value))); } - batchInsetrSql.AppendLine(";SELECT LAST_INSERT_ROWID();"); - if (MySqlIgnore) - { - batchInsetrSql.Remove(0, "INSERT INTO `".Length); - batchInsetrSql.Insert(0, "INSERT OR IGNORE INTO `"); - } - var result = batchInsetrSql.ToString(); - return result; + sb.Append(i == groupCount - 1 ? ") " : "), "); + i++; } + + sb.AppendLine(";SELECT LAST_INSERT_ROWID();"); + + if (MySqlIgnore) + { + sb.Remove(0, InsertPrefix.Length); + sb.Insert(0, InsertIgnorePrefix); + } + + return sb.ToString(); } - public object FormatValue(int i, string name, object value) + + public object FormatValue(int index, string name, object value) { if (value == null) - { return "NULL"; - } - else + + var type = UtilMethods.GetUnderType(value.GetType()); + + if (type == UtilConstants.DateType) { - var type = UtilMethods.GetUnderType(value.GetType()); - if (type == UtilConstants.DateType) - { - var date = value.ObjToDate(); - if (date < UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig)) - { - date = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig); - } - if (this.Context.CurrentConnectionConfig?.MoreSettings?.DisableMillisecond == true) - { - return "'" + date.ToString("yyyy-MM-dd HH:mm:ss") + "'"; - } - else - { - return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"; - } - } - else if (type.IsEnum()) - { - if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true) - { - return value.ToSqlValue(); - } - else - { - return Convert.ToInt64(value); - } - } - else if (type == UtilConstants.DateTimeOffsetType) - { - return GetDateTimeOffsetString(value); - } - else if (type == UtilConstants.ByteArrayType) - { - var parameterName = this.Builder.SqlParameterKeyWord + name + i; - this.Parameters.Add(new SugarParameter(parameterName, value)); - return parameterName; - } - else if (type == UtilConstants.BoolType) - { - return value.ObjToBool() ? "1" : "0"; - } - else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) - { - return "'" + value.ToString().ToSqlFilter() + "'"; - } - else - { - return "'" + value.ToString() + "'"; - } + var date = value.ObjToDate(); + var minDate = UtilMethods.GetMinDate(Context.CurrentConnectionConfig); + if (date < minDate) date = minDate; + + var format = Context.CurrentConnectionConfig?.MoreSettings?.DisableMillisecond == true + ? "yyyy-MM-dd HH:mm:ss" + : "yyyy-MM-dd HH:mm:ss.fff"; + return $"'{date.ToString(format)}'"; } + + if (type.IsEnum()) + { + if (Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true) + return value.ToSqlValue(); + else + return Convert.ToInt64(value); + } + + if (type == UtilConstants.DateTimeOffsetType) + return GetDateTimeOffsetString(value); + + if (type == UtilConstants.ByteArrayType) + { + var parameterName = $"{Builder.SqlParameterKeyWord}{name}{index}"; + Parameters.Add(new SugarParameter(parameterName, value)); + return parameterName; + } + + if (type == UtilConstants.BoolType) + return ((bool)value) ? "1" : "0"; + + if (type == UtilConstants.StringType || type == UtilConstants.ObjType) + return $"'{value.ToString().ToSqlFilter()}'"; + + return $"'{value}'"; } - private object GetDateTimeOffsetString(object value) + private string GetDateTimeOffsetString(object value) { var date = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)value); - if (date < UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig)) - { - date = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig); - } - return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fffffff") + "'"; - } - - private object GetDateTimeString(object value) - { - var date = value.ObjToDate(); - if (date < UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig)) - { - date = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig); - } - return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"; + var minDate = UtilMethods.GetMinDate(Context.CurrentConnectionConfig); + if (date < minDate) date = minDate; + return $"'{date:yyyy-MM-dd HH:mm:ss.fffffff}'"; } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqliteProvider.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqliteProvider.cs index d69107d01..ab733c7e5 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqliteProvider.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Realization/Sqlite/SqliteProvider.cs @@ -18,7 +18,7 @@ namespace ThingsGateway.SqlSugar var SQLiteConnectionString = base.Context.CurrentConnectionConfig.ConnectionString; if (SQLiteConnectionString?.Contains('=') == false) { - Check.ExceptionEasy("ConnString format error . Correct format DataSource=...", "字符串格式错误,应该是DataSource=..."); + Check.ExceptionLang("ConnString format error . Correct format DataSource=...", "字符串格式错误,应该是DataSource=..."); } base._DbConnection = new SqliteConnection(SQLiteConnectionString); } @@ -26,11 +26,11 @@ namespace ThingsGateway.SqlSugar { if (ex.InnerException != null) { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message + "\r\n" + ex.InnerException.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message + "\r\n" + ex.InnerException.Message); } } else { - Check.Exception(true, ErrorMessage.ConnnectionOpen, ex.Message); + { throw new SqlSugarException(ErrorMessage.ConnnectionOpen, ex.Message); } } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableAttribute.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableAttribute.cs index 179bf7ccf..765cb677c 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableAttribute.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableAttribute.cs @@ -14,7 +14,7 @@ this.SplitType = splitType; if (!customSplitTableService.GetInterfaces().Any(it => it == typeof(ISplitTableService))) { - Check.ExceptionEasy("customSplitTableService in SplitTableAttribute(SplitType splitType,Type customSplitTableService) must be inherited ISplitTableService", " SplitTableAttribute(SplitType splitType,Type customSplitTableService) 中的 customSplitTableService 必须继承 ISplitTableService"); + Check.ExceptionLang("customSplitTableService in SplitTableAttribute(SplitType splitType,Type customSplitTableService) must be inherited ISplitTableService", " SplitTableAttribute(SplitType splitType,Type customSplitTableService) 中的 customSplitTableService 必须继承 ISplitTableService"); } this.CustomSplitTableService = customSplitTableService; } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableContext.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableContext.cs index 22710c77f..b338d79c3 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/SpliteTable/SplitTableContext.cs @@ -15,7 +15,7 @@ namespace ThingsGateway.SqlSugar { List result = new List(); var attribute = typeof(T).GetCustomAttribute() as SplitTableAttribute; - Check.Exception(attribute == null, $" {typeof(T).Name} need SplitTableAttribute"); + if (attribute == null) { throw new SqlSugarException($" {typeof(T).Name} need SplitTableAttribute"); } foreach (var item in Items) { result.Add(Helper.GetTableName(Helper.GetValue(attribute.SplitType, item))); @@ -93,7 +93,7 @@ namespace ThingsGateway.SqlSugar public string GetTableName(object fieldValue) { var attribute = EntityInfo.Type.GetCustomAttribute() as SplitTableAttribute; - Check.Exception(attribute == null, $" {EntityInfo.EntityName} need SplitTableAttribute"); + if (attribute == null) { throw new SqlSugarException($" {EntityInfo.EntityName} need SplitTableAttribute"); } return Service.GetTableName(this.Context, EntityInfo, attribute.SplitType, fieldValue); } public object GetValue(SplitType splitType, object entityValue) @@ -102,7 +102,7 @@ namespace ThingsGateway.SqlSugar } internal void CheckPrimaryKey() { - Check.Exception(EntityInfo.Columns.Any(it => it.IsIdentity == true), ErrorMessage.GetThrowMessage("Split table can't IsIdentity=true", "分表禁止使用自增列")); + if (EntityInfo.Columns.Any(it => it.IsIdentity == true)) { throw new SqlSugarException(ErrorMessage.GetThrowMessage("Split table can't IsIdentity=true", "分表禁止使用自增列")); } } } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/SqlSugarClient.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/SqlSugarClient.cs index c44cff80a..e8474cda4 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/SqlSugarClient.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/SqlSugarClient.cs @@ -28,13 +28,13 @@ namespace ThingsGateway.SqlSugar #region Constructor public SqlSugarClient(ConnectionConfig config) { - Check.Exception(config == null, "ConnectionConfig config is null"); + if (config == null) { throw new SqlSugarException("ConnectionConfig config is null"); } InitContext(config); } public SqlSugarClient(List configs) { - Check.Exception(configs.IsNullOrEmpty(), "List configs is null or count=0"); + if (configs.IsNullOrEmpty()) { throw new SqlSugarException("List configs is null or count=0"); } InitConfigs(configs); var config = configs[0]; InitContext(config); @@ -44,7 +44,7 @@ namespace ThingsGateway.SqlSugar public SqlSugarClient(ConnectionConfig config, Action configAction) { _configAction = configAction; - Check.Exception(config == null, "ConnectionConfig config is null"); + if (config == null) { throw new SqlSugarException("ConnectionConfig config is null"); } InitContext(config); configAction(this); } @@ -52,7 +52,11 @@ namespace ThingsGateway.SqlSugar public SqlSugarClient(List configs, Action configAction) { _configAction = configAction; - Check.Exception(configs.IsNullOrEmpty(), "List configs is null or count=0"); + + if (configs.IsNullOrEmpty()) + { + throw new SqlSugarException("List configs is null or count=0"); + } InitConfigs(configs); var config = configs[0]; InitContext(config); @@ -173,10 +177,10 @@ namespace ThingsGateway.SqlSugar public IInsertable InsertableT(T insertObj) where T : class, new() { - Check.ExceptionEasy(typeof(T).FullName.Contains("System.Collections.Generic.List`"), " need where T: class, new() ", "需要Class,new()约束,并且类属性中不能有required修饰符"); + if (typeof(T).FullName.Contains("System.Collections.Generic.List`")) { throw new SqlSugarLangException(" need where T: class, new() ", "需要Class,new()约束,并且类属性中不能有required修饰符"); } if (typeof(T).Name == "Object") { - Check.ExceptionEasy("Object type use db.InsertableByObject(obj).ExecuteCommand()", "检测到T为Object类型,请使用 db.InsertableByObject(obj).ExecuteCommand(),Insertable不支持object,InsertableByObject可以(缺点:功能比较少)"); + Check.ExceptionLang("Object type use db.InsertableByObject(obj).ExecuteCommand()", "检测到T为Object类型,请使用 db.InsertableByObject(obj).ExecuteCommand(),Insertable不支持object,InsertableByObject可以(缺点:功能比较少)"); } return this.Context.InsertableT(insertObj); } @@ -544,7 +548,7 @@ namespace ThingsGateway.SqlSugar public IStorageable StorageableT(T data) where T : class, new() { - Check.Exception(typeof(T).FullName.Contains("System.Collections.Generic.List`"), " need where T: class, new() "); + if (typeof(T).FullName.Contains("System.Collections.Generic.List`")) { throw new SqlSugarException(" need where T: class, new() "); } return this.Context.Storageable(new List { data }); } @@ -815,18 +819,18 @@ namespace ThingsGateway.SqlSugar { if (removeData.Context.Ado.IsAnyTran()) { - Check.ExceptionEasy("RemoveConnection error has tran", $"删除失败{removeData.ConnectionConfig.ConfigId}存在未提交事务"); + Check.ExceptionLang("RemoveConnection error has tran", $"删除失败{removeData.ConnectionConfig.ConfigId}存在未提交事务"); } else if (((object)removeData.ConnectionConfig.ConfigId).ObjToString() == currentId.ObjToString()) { - Check.ExceptionEasy("Default ConfigId cannot be deleted", $"默认库不能删除{removeData.ConnectionConfig.ConfigId}"); + Check.ExceptionLang("Default ConfigId cannot be deleted", $"默认库不能删除{removeData.ConnectionConfig.ConfigId}"); } this._AllClients.Remove(removeData); } } public void AddConnection(ConnectionConfig connection) { - Check.ArgumentNullException(connection, "AddConnection.connection can't be null"); + if (connection == null) { throw new SqlSugarException("AddConnection.connection can't be null"); } InitTenant(); var db = this._AllClients.FirstOrDefault(it => ((object)it.ConnectionConfig.ConfigId).ObjToString() == ((object)connection.ConfigId).ObjToString()); if (db == null) @@ -877,7 +881,7 @@ namespace ThingsGateway.SqlSugar var db = this._AllClients.FirstOrDefault(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId)); if (db == null) { - Check.Exception(true, "ConfigId was not found {0}", configId + ""); + { throw new SqlSugarException($"ConfigId was not found {configId}"); } } if (db.Context == null) { @@ -915,7 +919,7 @@ namespace ThingsGateway.SqlSugar { configId = Convert.ToString(configId); var isLog = _Context.Ado.IsEnableLogEvent; - Check.Exception(!_AllClients.Any(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId)), "ConfigId was not found {0}", configId + ""); + if (!_AllClients.Any(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId))) { throw new SqlSugarException($"ConfigId was not found {configId}"); } InitTenant(_AllClients.First(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId))); if (this._IsAllTran) this.Ado.BeginTran(); @@ -929,7 +933,7 @@ namespace ThingsGateway.SqlSugar { var isLog = _Context.Ado.IsEnableLogEvent; var allConfigs = _AllClients.Select(it => it.ConnectionConfig); - Check.Exception(!allConfigs.Any(changeExpression), "changeExpression was not found {0}", changeExpression.ToString()); + if (!allConfigs.Any(changeExpression)) { throw new SqlSugarException("changeExpression was not found {0}", changeExpression.ToString()); } InitTenant(_AllClients.First(it => it.ConnectionConfig == allConfigs.First(changeExpression))); if (this._IsAllTran) this.Ado.BeginTran(); diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/Check.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/Check.cs index 920ad41d1..4c318c604 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/Check.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/Check.cs @@ -1,43 +1,20 @@ -using System.Text; -namespace ThingsGateway.SqlSugar +namespace ThingsGateway.SqlSugar { public static class Check { public static void ThrowNotSupportedException(string message) { message = message.IsNullOrEmpty() ? new NotSupportedException().Message : message; - throw new SqlSugarException("SqlSugarException.NotSupportedException:" + message); + throw new SqlSugarException($"SqlSugarException.NotSupportedException:{message}"); } - public static void ArgumentNullException(object checkObj, string message) - { - if (checkObj == null) - throw new SqlSugarException("SqlSugarException.ArgumentNullException:" + message); - } - public static void ArgumentNullException(object[] checkObj, string message) - { - if (checkObj == null || checkObj.Length == 0) - throw new SqlSugarException("SqlSugarException.ArgumentNullException:" + message); - } - public static void Exception(bool isException, CompositeFormat compositeFormat, params string[] args) - { - if (isException) - throw new SqlSugarException(string.Format(null, compositeFormat, args)); - } - public static void Exception(bool isException, string message, params string[] args) - { - if (isException) - throw new SqlSugarException(string.Format(message, args)); - } - public static void ExceptionEasy(string enMessage, string cnMessage) + + public static void ExceptionLang(string enMessage, string cnMessage) { throw new SqlSugarException(ErrorMessage.GetThrowMessage(enMessage, cnMessage)); } - public static void ExceptionEasy(bool isException, string enMessage, string cnMessage) - { - if (isException) - throw new SqlSugarException(ErrorMessage.GetThrowMessage(enMessage, cnMessage)); - } + + } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/DbExtensions.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/DbExtensions.cs index 88a3c2e2f..60f22cd8d 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/DbExtensions.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/DbExtensions.cs @@ -118,15 +118,15 @@ namespace ThingsGateway.SqlSugar } else if (IsUpdateSql(value, "/", "/")) { - Check.ExceptionEasy($"{value} format error ", value + "不能存在 /+【update drop 等】+/ "); + Check.ExceptionLang($"{value} format error ", value + "不能存在 /+【update drop 等】+/ "); } else if (IsUpdateSql(value, "/", " ")) { - Check.ExceptionEasy($"{value} format error ", value + "不能存在 /+【update drop 等】+空格 "); + Check.ExceptionLang($"{value} format error ", value + "不能存在 /+【update drop 等】+空格 "); } else if (IsUpdateSql(value, " ", "/")) { - Check.ExceptionEasy($"{value} format error ", value + "不能存在 空格+【update drop 等】+/ "); + Check.ExceptionLang($"{value} format error ", value + "不能存在 空格+【update drop 等】+/ "); } else if (value.Contains(" update ", StringComparison.CurrentCultureIgnoreCase) || value.Contains(" delete ", StringComparison.CurrentCultureIgnoreCase) @@ -135,7 +135,7 @@ namespace ThingsGateway.SqlSugar || value.Contains(" create ", StringComparison.CurrentCultureIgnoreCase) || value.Contains(" insert ", StringComparison.CurrentCultureIgnoreCase)) { - Check.ExceptionEasy($"{value} format error ", value + "不能存在 空格+【update drop 等】+空格 "); + Check.ExceptionLang($"{value} format error ", value + "不能存在 空格+【update drop 等】+空格 "); } } return value; diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ErrorMessage.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ErrorMessage.cs index 915138962..33d119525 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ErrorMessage.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ErrorMessage.cs @@ -9,17 +9,11 @@ namespace ThingsGateway.SqlSugar private static readonly CompositeFormat privateEObjNotExistCompositeFormat = CompositeFormat.Parse("{0} does not exist."); private static readonly CompositeFormat privateCObjNotExistCompositeFormat = CompositeFormat.Parse("{0}不存在。"); - internal static CompositeFormat EntityMappingErrorCompositeFormat => SugarLanguageType == LanguageType.English ? privateEEntityMappingErrorCompositeFormat : privateCEntityMappingErrorCompositeFormat; - private static readonly CompositeFormat privateEEntityMappingErrorCompositeFormat = CompositeFormat.Parse("Entity mapping error.{0}"); - private static readonly CompositeFormat privateCEntityMappingErrorCompositeFormat = CompositeFormat.Parse("Select 实体与表映射出错,可以注释实体类中的字段排查具体哪一个字段。【注意:如果用CodeFirt先配置禁止删列或更新】 {0}"); + internal const string EntityMappingErrorCompositeFormat = "Select entity and table mapping error, you can annotate the fields in the entity class to investigate which specific field. [Note: If CodeFirt is used, configure to prohibit column deletion or updates first] . "; - internal static CompositeFormat NotSupportedDictionaryCompositeFormat => SugarLanguageType == LanguageType.English ? privateENotSupportedDictionaryCompositeFormat : privateCNotSupportedDictionaryCompositeFormat; - private static readonly CompositeFormat privateENotSupportedDictionaryCompositeFormat = CompositeFormat.Parse("This type of Dictionary is not supported for the time being. You can try Dictionary, or contact the author!"); - private static readonly CompositeFormat privateCNotSupportedDictionaryCompositeFormat = CompositeFormat.Parse("暂时不支持该类型的Dictionary 你可以试试 Dictionary或者联系作者!"); + internal const string NotSupportedDictionaryCompositeFormat = "This type of Dictionary is not supported for the time being. You can try Dictionary"; - internal static CompositeFormat NotSupportedArrayCompositeFormat => SugarLanguageType == LanguageType.English ? privateENotSupportedArrayCompositeFormat : privateCNotSupportedArrayCompositeFormat; - private static readonly CompositeFormat privateENotSupportedArrayCompositeFormat = CompositeFormat.Parse("This type of Array is not supported for the time being. You can try object[] or contact the author!"); - private static readonly CompositeFormat privateCNotSupportedArrayCompositeFormat = CompositeFormat.Parse("暂时不支持该类型的Array 你可以试试 object[] 或者联系作者!"); + internal const string NotSupportedArrayCompositeFormat = "This type of Array is not supported for the time being. You can try object[]"; internal static string GetThrowMessage(string enMessage, string cnMessage, params string[] args) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilExceptions.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilExceptions.cs index 91a1c8bd3..a2ae935e1 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilExceptions.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilExceptions.cs @@ -12,7 +12,8 @@ namespace ThingsGateway.SqlSugar public SqlSugarException(string message) : base(message) { } - + public SqlSugarException(string message, params object[] strings) + : base(string.Format(message, strings)) { } public SqlSugarException(SqlSugarProvider context, string message, string sql) : base(message) { @@ -80,4 +81,34 @@ namespace ThingsGateway.SqlSugar { } } + + public class SqlSugarLangException : SqlSugarException + { + public SqlSugarLangException(string enmessage, string cnMessage) + : base(ErrorMessage.GetThrowMessage(enmessage, cnMessage)) { } + + public SqlSugarLangException(SqlSugarProvider context, string message, string sql) : base(context, message, sql) + { + } + + public SqlSugarLangException(SqlSugarProvider context, string message, string sql, IReadOnlyCollection pars) : base(context, message, sql, pars) + { + } + + public SqlSugarLangException(SqlSugarProvider context, Exception ex, string sql, IReadOnlyCollection pars) : base(context, ex, sql, pars) + { + } + + public SqlSugarLangException(SqlSugarProvider context, string message, IReadOnlyCollection pars) : base(context, message, pars) + { + } + + public SqlSugarLangException() : base() + { + } + + public SqlSugarLangException(string? message, Exception? innerException) : base(message, innerException) + { + } + } } diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilMethods.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilMethods.cs index 3f2846178..6806cc9ad 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilMethods.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/UtilMethods.cs @@ -1084,8 +1084,21 @@ namespace ThingsGateway.SqlSugar { return (T)To(value, typeof(T)); } - public static readonly DateTime MinDate = Convert.ToDateTime("1900-01-01"); - + public static readonly DateTime MinDate = ToDate("1900-01-01"); + internal static DateTime ToDateTime(string dateTime) + { + var format = "yyyy-MM-dd HH:mm:ss"; + var provider = CultureInfo.InvariantCulture; + DateTime dt = DateTime.ParseExact(dateTime, format, provider); + return dt; + } + internal static DateTime ToDate(string dateTime) + { + var format = "yyyy-MM-dd"; + var provider = CultureInfo.InvariantCulture; + DateTime dt = DateTime.ParseExact(dateTime, format, provider); + return dt; + } internal static DateTime GetMinDate(ConnectionConfig currentConnectionConfig) { if (currentConnectionConfig.MoreSettings == null) @@ -1868,7 +1881,7 @@ namespace ThingsGateway.SqlSugar } else if (item.IsArray) { - result = result.Replace(item.ParameterName, "'{" + new SerializeService().SerializeObject(item.Value).TrimStart('[').TrimEnd(']') + "}'"); + result = result.Replace(item.ParameterName, "'{" + DefaultServices.Serialize.SerializeObject(item.Value).TrimStart('[').TrimEnd(']') + "}'"); } else if (item.Value is byte[] && connectionConfig.DbType == DbType.PostgreSQL) { @@ -1992,7 +2005,7 @@ namespace ThingsGateway.SqlSugar var entityInfo = queryable.Context?.EntityMaintenance?.GetEntityInfoWithAttr(type); if (entityInfo?.Discrimator.HasValue() == true) { - Check.ExceptionEasy(!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); + if (!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$")) { throw new SqlSugarLangException("The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); } var array = entityInfo.Discrimator.Split(','); foreach (var disItem in array) { @@ -2007,7 +2020,7 @@ namespace ThingsGateway.SqlSugar List wheres = new List(); if (entityInfo?.Discrimator.HasValue() == true) { - Check.ExceptionEasy(!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); + if (!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$")) { throw new SqlSugarLangException("The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); } var array = entityInfo.Discrimator.Split(','); foreach (var disItem in array) { diff --git a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ValidateExtensions.cs b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ValidateExtensions.cs index 3c6298eff..3e8f09409 100644 --- a/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ValidateExtensions.cs +++ b/src/Admin/ThingsGateway.SqlSugar/Sugar/Utilities/ValidateExtensions.cs @@ -43,7 +43,11 @@ namespace ThingsGateway.SqlSugar if (thisValue == null || thisValue == DBNull.Value) return true; return string.IsNullOrEmpty(thisValue.ToString()); } - + public static bool IsNullOrEmpty(this string thisValue) + { + if (thisValue == null) return true; + return string.IsNullOrEmpty(thisValue); + } public static bool IsNullOrEmpty(this Guid? thisValue) { if (thisValue == null) return true; diff --git a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/CodeFirst/TDengineCodeFirst.cs b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/CodeFirst/TDengineCodeFirst.cs index 77455b3ac..230433e83 100644 --- a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/CodeFirst/TDengineCodeFirst.cs +++ b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/CodeFirst/TDengineCodeFirst.cs @@ -25,7 +25,7 @@ namespace ThingsGateway.SqlSugar //var entityInfo = this.Context.EntityMaintenance.GetEntityInfoNoCache(entityType); if (entityInfo.Discrimator.HasValue()) { - Check.ExceptionEasy(!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$"), "The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); + if (!Regex.IsMatch(entityInfo.Discrimator, @"^(?:\w+:\w+)(?:,\w+:\w+)*$")) { throw new SqlSugarLangException("The format should be type:cat for this type, and if there are multiple, it can be FieldName:cat,FieldName2:dog ", "格式错误应该是type:cat这种格式,如果是多个可以FieldName:cat,FieldName2:dog,不要有空格"); } var array = entityInfo.Discrimator.Split(','); foreach (var disItem in array) { @@ -104,7 +104,7 @@ namespace ThingsGateway.SqlSugar { if (entityInfo.Columns.HasValue() && entityInfo.IsDisabledUpdateAll == false) { - //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Multiple primary keys do not support modifications"); + //if(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1){throw new SqlSugarException("Multiple primary keys do not support modifications");} var tableName = GetTableName(entityInfo); var dbColumns = this.Context.DbMaintenance.GetColumnInfosByTableName(tableName, false); diff --git a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/DbMaintenance/TDengineDbMaintenance.cs b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/DbMaintenance/TDengineDbMaintenance.cs index a46baf407..2e117e6e4 100644 --- a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/DbMaintenance/TDengineDbMaintenance.cs +++ b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/DbMaintenance/TDengineDbMaintenance.cs @@ -562,7 +562,7 @@ namespace ThingsGateway.SqlSugar protected override string GetCreateTableSql(string tableName, List columns) { List columnArray = new List(); - Check.Exception(columns.IsNullOrEmpty(), "No columns found "); + if (columns.IsNullOrEmpty()) { throw new SqlSugarException("No columns found "); } foreach (var item in columns) { string columnName = item.DbColumnName; diff --git a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TDengineInserttable.cs b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TDengineInserttable.cs index cb1984ea4..6194d8efd 100644 --- a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TDengineInserttable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TDengineInserttable.cs @@ -94,7 +94,7 @@ var identityKeys = GetIdentityKeys(); if (identityKeys.Count == 0) { return this.ExecuteCommand() > 0; } var idValue = ExecuteReturnBigIdentity(); - Check.Exception(identityKeys.Count > 1, "ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); + if (identityKeys.Count > 1) { throw new SqlSugarException("ExecuteCommandIdentityIntoEntity does not support multiple identity keys"); } var identityKey = identityKeys[0]; object setValue = 0; if (idValue > int.MaxValue) diff --git a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TagInserttable.cs b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TagInserttable.cs index 4b67fe076..bb36b151a 100644 --- a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TagInserttable.cs +++ b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/Insertable/TagInserttable.cs @@ -32,7 +32,7 @@ namespace ThingsGateway.SqlSugar var provider = (InsertableProvider)thisValue; var inserObjects = provider.InsertObjs; var attr = GetCommonSTableAttribute(typeof(T).GetCustomAttribute()); - Check.ExceptionEasy(attr == null || attr?.Tag1 == null, $"", $"{nameof(T)}缺少特性STableAttribute和Tag1"); + if (attr == null || attr?.Tag1 == null) { throw new SqlSugarLangException($"", $"{nameof(T)}缺少特性STableAttribute和Tag1"); } // 根据所有非空的 Tag 进行分组 var groups = GetGroupInfos(inserObjects, attr); foreach (var item in groups) @@ -61,7 +61,7 @@ namespace ThingsGateway.SqlSugar var provider = (InsertableProvider)thisValue; var inserObjects = provider.InsertObjs; var attr = GetCommonSTableAttribute(typeof(T).GetCustomAttribute()); - Check.ExceptionEasy(attr == null || attr?.Tag1 == null, $"", $"{nameof(T)}缺少特性STableAttribute和Tag1"); + if (attr == null || attr?.Tag1 == null) { throw new SqlSugarLangException($"", $"{nameof(T)}缺少特性STableAttribute和Tag1"); } // 根据所有非空的 Tag 进行分组 var groups = GetGroupInfos(inserObjects, attr); foreach (var item in groups) diff --git a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineBuilder.cs b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineBuilder.cs index 8cb3e4060..a381b9ec2 100644 --- a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineBuilder.cs +++ b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineBuilder.cs @@ -95,8 +95,8 @@ /// 转换后的列名 public override string GetTranslationColumnName(string entityName, string propertyName) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); - Check.ArgumentNullException(propertyName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } + if (propertyName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } var context = this.Context; var mappingInfo = context .MappingColumns @@ -113,7 +113,7 @@ /// 转换后的表名 public override string GetTranslationTableName(string name) { - Check.ArgumentNullException(name, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (name == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } var context = this.Context; var mappingInfo = context diff --git a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineExpressionContext.cs b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineExpressionContext.cs index 99ee6d562..01ec36e13 100644 --- a/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineExpressionContext.cs +++ b/src/Admin/ThingsGateway.SqlSugar/TDengine/TDengine/SqlBuilder/TDengineExpressionContext.cs @@ -70,7 +70,7 @@ namespace ThingsGateway.SqlSugar /// 转换后的表名 public override string GetTranslationTableName(string entityName, bool isMapping = true) { - Check.ArgumentNullException(entityName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); + if (entityName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Table Name")); } if (IsTranslationText(entityName)) return entityName; isMapping = isMapping && this.MappingTables.HasValue(); var isComplex = entityName.Contains(UtilConstants.Dot); @@ -114,7 +114,7 @@ namespace ThingsGateway.SqlSugar /// 转换后的列名 public override string GetTranslationColumnName(string columnName) { - Check.ArgumentNullException(columnName, string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); + if (columnName == null) { throw new SqlSugarException(string.Format(null, ErrorMessage.ObjNotExistCompositeFormat, "Column Name")); } if (columnName.Substring(0, 1) == this.SqlParameterKeyWord) { return columnName; diff --git a/src/Plugin/ThingsGateway.Plugin.DB/SqlDB/SplitTable/SqlDBDateSplitTableService.cs b/src/Plugin/ThingsGateway.Plugin.DB/SqlDB/SplitTable/SqlDBDateSplitTableService.cs index 5599729ae..8d589e2a5 100644 --- a/src/Plugin/ThingsGateway.Plugin.DB/SqlDB/SplitTable/SqlDBDateSplitTableService.cs +++ b/src/Plugin/ThingsGateway.Plugin.DB/SqlDB/SplitTable/SqlDBDateSplitTableService.cs @@ -86,13 +86,13 @@ public class SqlDBDateSplitTableService : DateSplitTableService private static void CheckTableName(string dbTableName) { - Check.Exception(!dbTableName.Contains("{year}"), "table name need {{year}}", "分表表名需要占位符 {{year}}"); - Check.Exception(!dbTableName.Contains("{month}"), "table name need {{month}}", "分表表名需要占位符 {{month}} "); - Check.Exception(!dbTableName.Contains("{day}"), "table name need {{day}}", "分表表名需要占位符{{day}}"); - Check.Exception(_yearRegex.Count(dbTableName) > 1, " There can only be one {{year}}", " 只能有一个 {{year}}"); - Check.Exception(_monthRegex.Count(dbTableName) > 1, "There can only be one {{month}}", "只能有一个 {{month}} "); - Check.Exception(_dayRegex.Count(dbTableName) > 1, "There can only be one {{day}}", "只能有一个{{day}}"); - Check.Exception(_regex.IsMatch(dbTableName), " '{{' or '}}' can't be numbers nearby", "占位符相令一位不能是数字,比如 : 1{{day}}2 错误 , 正确: 1_{{day}}_2"); + if (!dbTableName.Contains("{year}")) throw new SqlSugarException("table name need {{year}}", "分表表名需要占位符 {{year}}"); + if (!dbTableName.Contains("{month}")) throw new SqlSugarException("table name need {{month}}", "分表表名需要占位符 {{month}} "); + if (!dbTableName.Contains("{day}")) throw new SqlSugarException("table name need {{day}}", "分表表名需要占位符{{day}}"); + if (_yearRegex.Count(dbTableName) > 1) throw new SqlSugarException(" There can only be one {{year}}", " 只能有一个 {{year}}"); + if (_monthRegex.Count(dbTableName) > 1) throw new SqlSugarException("There can only be one {{month}}", "只能有一个 {{month}} "); + if (_dayRegex.Count(dbTableName) > 1) throw new SqlSugarException("There can only be one {{day}}", "只能有一个{{day}}"); + if (_regex.IsMatch(dbTableName)) throw new SqlSugarException(" '{{' or '}}' can't be numbers nearby", "占位符相令一位不能是数字,比如 : 1{{day}}2 错误 , 正确: 1_{{day}}_2"); } private static DateTime GetDate(string group1, string group2, string group3, string dbTableName)