You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
3.4 KiB

using Apewer;
using Apewer.Internals;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace Apewer.Source
{
/// <summary>数据库记录通用字段模型。</summary>
/// <remarks>带有 Independent 特性的模型不包含此类型声明的属性。</remarks>
[Serializable]
public abstract class Record : IRecord
{
const int KeyLength = 191;
private string _key = null;
private long _flag = 0;
/// <summary>记录主键,一般使用 GUID 的字符串形式。</summary>
/// <remarks>带有 Independent 特性的模型不包含此属性。</remarks>
[Column("_key", ColumnType.NVarChar, KeyLength)]
public string Key { get { return _key; } set { _key = Compact(value, KeyLength); } }
/// <summary>记录的标记,Int64 类型,区分记录的状态。</summary>
/// <remarks>带有 Independent 特性的模型不包含此属性。</remarks>
[Column("_flag", ColumnType.Integer)]
public long Flag { get { return _flag; } set { _flag = value; } }
/// <summary>重置 Key 属性的值。</summary>
public virtual void ResetKey() => _key = TextUtility.Key();
/// <summary></summary>
public Record() => ResetKey();
#region static
/// <summary>枚举带有 Table 特性的 <typeparamref name="T"/> 派生类型。</summary>
public static List<Type> EnumerateTableTypes<T>() where T : IRecord => EnumerateTableTypes(typeof(T));
/// <summary>枚举带有 Table 特性的派生类型。</summary>
public static List<Type> EnumerateTableTypes(Type baseType)
{
if (baseType == null) return new List<Type>();
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var list = new List<Type>();
foreach (var a in assemblies)
{
var types = RuntimeUtility.GetTypes(a);
foreach (var t in types)
{
if (!EnumerateTableTypes(t, baseType)) continue;
if (list.Contains(t)) continue;
list.Add(t);
}
}
return list;
}
private static bool EnumerateTableTypes(Type type, Type @base)
{
if (type == null || @base == null) return false;
if (!type.IsAbstract)
{
if (RuntimeUtility.Contains<TableAttribute>(type, false))
{
if (type.Equals(@base))
{
return true;
}
else
{
if (RuntimeUtility.IsInherits(type, @base)) return true; ;
}
}
}
return false;
}
// 限制文本长度,并去除两边的空白字符。
static string Compact(string text, int length = -1)
{
if (string.IsNullOrEmpty(text)) return "";
if (length > 0 && text.Length > length) text = text.Substring(0, length);
return text.Trim();
}
#endregion
#region 运算符。
/// <summary>从 Record 到 Boolean 的隐式转换,判断 Record 对象不为 NULL。</summary>
public static implicit operator bool(Record instance) => instance != null;
#endregion
}
}