/// <summary> /// 自动扫描迁移模型并添加表和列说明 /// </summary> /// <param name="migrationBuilder">迁移构造器</param> /// <param name="migration">迁移类实例</param> /// <param name="entityAssembly">实体类所在程序集</param> /// <param name="schema">架构</param> public static void AddDatabaseDescription(this MigrationBuilder migrationBuilder, Migration migration, Assembly entityAssembly) { if (entityAssembly == null) { throw new NullReferenceException($"{nameof(entityAssembly)} cannot be null."); } foreach (var entityType in migration.TargetModel.GetEntityTypes().Select(entity => new { EntityType = entity, ClrType = entityAssembly.GetType(entity.Name) })) { //添加表说明 if (entityType.ClrType?.CustomAttributes.Any( attr => attr.AttributeType == typeof(DbDescriptionAttribute)) == true) { migrationBuilder.AddTableDescription(entityType.EntityType.Relational().TableName, (entityType.ClrType.GetCustomAttribute(typeof(DbDescriptionAttribute)) as DbDescriptionAttribute )?.Description, entityType.EntityType.Relational().Schema); } //添加列说明 foreach (var property in entityType.EntityType.GetProperties()) { if (entityType.ClrType?.GetProperty(property.Name)?.CustomAttributes .Any(attr => attr.AttributeType == typeof(DbDescriptionAttribute)) == true) { //如果该列的实体属性是枚举类型,把枚举的说明追加到列说明 var enumDbDescription = string.Empty; if (entityType.ClrType?.GetProperty(property.Name)?.PropertyType.IsEnum == true || (entityType.ClrType?.GetProperty(property.Name)?.PropertyType .HasImplementedRawGeneric(typeof(Nullable <>)) == true && entityType.ClrType?.GetProperty(property.Name)?.PropertyType.GenericTypeArguments[0] .IsEnum == true)) { var @enum = entityType.ClrType?.GetProperty(property.Name)?.PropertyType .HasImplementedRawGeneric(typeof(Nullable <>)) == true ? entityType.ClrType?.GetProperty(property.Name)?.PropertyType.GenericTypeArguments[0] : entityType.ClrType?.GetProperty(property.Name)?.PropertyType; var descList = new List <string>(); foreach (var field in @enum?.GetFields() ?? new FieldInfo[0]) { if (!field.IsSpecialName) { var desc = (field.GetCustomAttributes(typeof(DbDescriptionAttribute), false) .FirstOrDefault() as DbDescriptionAttribute)?.Description; descList.Add( $@"{field.GetRawConstantValue()} : {(desc.IsNullOrWhiteSpace() ? field.Name : desc)}"); } } var enumTypeDbDescription = (@enum?.GetCustomAttributes(typeof(DbDescriptionAttribute), false).FirstOrDefault() as DbDescriptionAttribute)?.Description; enumDbDescription = $@"( {(enumTypeDbDescription.IsNullOrWhiteSpace() ? "" : $@"{enumTypeDbDescription}; ")}{string.Join("; ", descList)} )"; } migrationBuilder.AddColumnDescription(entityType.EntityType.Relational().TableName, property.Relational().ColumnName, $@"{(entityType.ClrType?.GetProperty(property.Name) ?.GetCustomAttribute(typeof(DbDescriptionAttribute)) as DbDescriptionAttribute) ?.Description}{(enumDbDescription.IsNullOrWhiteSpace() ? "" : $@" {enumDbDescription}")}"