扩展属性,查询是否定义特定特性

This commit is contained in:
falcon 2022-10-10 18:21:16 +08:00
parent c2e3c29b70
commit 511bfab781
2 changed files with 44 additions and 6 deletions

View File

@ -24,15 +24,28 @@ namespace Falcon.SugarApi.DatabaseDefinitions
this.ConfigureExternalServices ??= new ConfigureExternalServices { }; this.ConfigureExternalServices ??= new ConfigureExternalServices { };
//设置Nullable //设置Nullable
this.ConfigureExternalServices.EntityService += (p, c) => { this.ConfigureExternalServices.EntityService += (p, c) => {
if (p.GetCustomAttribute<RequiredAttribute>() != null) {
c.IsNullable = false;
return;
}
var pt = p.PropertyType; var pt = p.PropertyType;
//所有类型默认可空
bool na = true;
//字符串默认可空
na = pt == typeof(string) ? true : na;
//Nullable<>类型可空
if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>)) {
c.IsNullable = true; na = true;
return;
} }
//RequiredAttribute标记不可空
if (p.GetCustomAttribute<RequiredAttribute>() != null) {
na = false;
}
//主键不可以为空
if (p.TryGetAttribute<KeyAttribute>(out var _)) {
na = false;
}
//定义主键不可以为空
if (p.TryGetAttribute<SugarColumn>(out var sc) && sc.IsPrimaryKey) {
na = false;
}
c.IsNullable = na;
//var sc = pt.GetCustomAttribute<SugarColumn>(); //var sc = pt.GetCustomAttribute<SugarColumn>();
//if (sc != null) { //if (sc != null) {
// c.IsNullable = sc.IsNullable; // c.IsNullable = sc.IsNullable;

View File

@ -0,0 +1,25 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace Falcon.SugarApi
{
/// <summary>
/// 类型相关扩展
/// </summary>
public static class TypeExtend
{
/// <summary>
/// 尝试获取Attribute
/// </summary>
/// <typeparam name="T">Attribute类型</typeparam>
/// <param name="info">属性</param>
/// <param name="p">定义的特性</param>
/// <returns>定义返回True否则False</returns>
public static bool TryGetAttribute<T>([NotNull] this PropertyInfo info, out T p) where T : Attribute {
p = info.GetCustomAttribute<T>();
return p != null;
}
}
}