From 511bfab781d05ddbf423f2b6e6cb8a6b3785f166 Mon Sep 17 00:00:00 2001 From: falcon <9504402@qq.com> Date: Mon, 10 Oct 2022 18:21:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=89=A9=E5=B1=95=E5=B1=9E=E6=80=A7=EF=BC=8C?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E6=98=AF=E5=90=A6=E5=AE=9A=E4=B9=89=E7=89=B9?= =?UTF-8?q?=E5=AE=9A=E7=89=B9=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SugarConnectionConfig.cs | 25 ++++++++++++++----- Falcon.SugarApi/TypeExtend.cs | 25 +++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) create mode 100644 Falcon.SugarApi/TypeExtend.cs diff --git a/Falcon.SugarApi/DatabaseDefinitions/SugarConnectionConfig.cs b/Falcon.SugarApi/DatabaseDefinitions/SugarConnectionConfig.cs index a422a01..dcb8822 100644 --- a/Falcon.SugarApi/DatabaseDefinitions/SugarConnectionConfig.cs +++ b/Falcon.SugarApi/DatabaseDefinitions/SugarConnectionConfig.cs @@ -24,15 +24,28 @@ namespace Falcon.SugarApi.DatabaseDefinitions this.ConfigureExternalServices ??= new ConfigureExternalServices { }; //设置Nullable this.ConfigureExternalServices.EntityService += (p, c) => { - if (p.GetCustomAttribute() != null) { - c.IsNullable = false; - return; - } var pt = p.PropertyType; + //所有类型默认可空 + bool na = true; + //字符串默认可空 + na = pt == typeof(string) ? true : na; + //Nullable<>类型可空 if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>)) { - c.IsNullable = true; - return; + na = true; } + //RequiredAttribute标记不可空 + if (p.GetCustomAttribute() != null) { + na = false; + } + //主键不可以为空 + if (p.TryGetAttribute(out var _)) { + na = false; + } + //定义主键不可以为空 + if (p.TryGetAttribute(out var sc) && sc.IsPrimaryKey) { + na = false; + } + c.IsNullable = na; //var sc = pt.GetCustomAttribute(); //if (sc != null) { // c.IsNullable = sc.IsNullable; diff --git a/Falcon.SugarApi/TypeExtend.cs b/Falcon.SugarApi/TypeExtend.cs new file mode 100644 index 0000000..0178c11 --- /dev/null +++ b/Falcon.SugarApi/TypeExtend.cs @@ -0,0 +1,25 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +namespace Falcon.SugarApi +{ + /// + /// 类型相关扩展 + /// + public static class TypeExtend + { + + /// + /// 尝试获取Attribute + /// + /// Attribute类型 + /// 属性 + /// 定义的特性 + /// 定义返回True,否则False + public static bool TryGetAttribute([NotNull] this PropertyInfo info, out T p) where T : Attribute { + p = info.GetCustomAttribute(); + return p != null; + } + } +}