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; + } + } +}