diff --git a/Apewer/Source/NotNullAttribute.cs b/Apewer/Source/NotNullAttribute.cs new file mode 100644 index 0000000..737a84c --- /dev/null +++ b/Apewer/Source/NotNullAttribute.cs @@ -0,0 +1,16 @@ +using System; + +namespace Apewer.Source +{ + + /// 字段不能是 NULL 值。 + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + public sealed class NotNullAttribute : Attribute + { + + /// + public override string ToString() => "Not Null"; + + } + +} diff --git a/Apewer/Source/SourceUtility.cs b/Apewer/Source/SourceUtility.cs index 176b1d5..d5a7834 100644 --- a/Apewer/Source/SourceUtility.cs +++ b/Apewer/Source/SourceUtility.cs @@ -337,6 +337,80 @@ namespace Apewer.Source if (stamp.Created == 0L) stamp.Created = now; if (stamp.Updated == 0L) stamp.Updated = now; } + + // 类型缓存 + var DateTimeType = typeof(DateTime); + var MinDateTime = new DateTime(1753, 1, 1, 0, 0, 0, 0); + var MaxDateTime = new DateTime(9999, 12, 31, 23, 59, 59, 997); + var NullableDateTimeType = typeof(DateTime?); + var StringType = typeof(string); + +#if DEBUG // 待测试 + + // 遍历字段 + var recordType = record.GetType(); + var tableStructure = TableStructure.Parse(recordType); + foreach (var column in tableStructure.Columns) + { + // 字符串 NOT NULL + if (column.Property.PropertyType.Equals(StringType)) + { + var value = column.Property.GetGetMethod().Invoke(record, null); + if (value == null) + { + var notNull = RuntimeUtility.GetAttribute(column.Property); + if (notNull != null) + { + column.Property.GetSetMethod().Invoke(record, new object[] { "" }); + } + } + continue; + } + + // DateTime + // min = 1753-01-01 00:00:00.000 + // max = 9999-12-31 23:59:59.997 + if (column.Property.PropertyType.Equals(DateTimeType)) + { + var value = (DateTime)column.Property.GetGetMethod().Invoke(record, null); + if (value < MinDateTime) + { + column.Property.GetSetMethod().Invoke(record, new object[] { MinDateTime }); + } + else if (value > MaxDateTime) + { + column.Property.GetSetMethod().Invoke(record, new object[] { MaxDateTime }); + } + continue; + } + if (column.Property.PropertyType.Equals(NullableDateTimeType)) + { + var value = (DateTime?)column.Property.GetGetMethod().Invoke(record, null); + if (value == null) + { + var notNull = RuntimeUtility.GetAttribute(column.Property); + if (notNull != null) + { + column.Property.GetSetMethod().Invoke(record, new object[] { MinDateTime }); + } + } + else + { + if (value < MinDateTime) + { + column.Property.GetSetMethod().Invoke(record, new object[] { MinDateTime }); + } + else if (value > MaxDateTime) + { + column.Property.GetSetMethod().Invoke(record, new object[] { MaxDateTime }); + } + } + continue; + } + } + +#endif + } /// 设置 Updated 属性。