freesql 生成数据库表结构文档
前言
目前有需求要这边提供系统的数据库表结构。随着系统的不断优化和迭代,数据库表不断增加,人工的维护不太现实,需要写一个小程序自动去生成表结构
整体思路
数据库的表结构,通过研究可以通过freesql的 dbFrist来获取,以下是freesql官方提供的一些方法
var t2 = fsql.DbFirst.GetTablesByDatabase(fsql.DbFirst.GetDatabases()[0]);
//返回包括表、列详情、主键、唯一键、索引、外键、备注等等
var t3 = fsql.DbFirst.GetTableByName("table1");
//返回表的列详情、主键、唯一键、索引、备注等等
获取到数据后,后续就是梳理出文档来,这里用 markdown格式来存储数据库结构。
header 来存储 表名
table 来存储表结构 ( field ,Type, Null,Key, Default, Remark)
markdown文档的构建使用类库 Julmar.GenMarkdown 来实现。
具体实现
代码很简单
string dbConnStr = "server=**"; IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, dbConnStr) .UseAdoConnectionPool(true) .UseMappingPriority(MappingPriorityType.FluentApi, MappingPriorityType.Attribute, MappingPriorityType.Aop) //.UseGenerateCommandParameterWithLambda(true) .UseMonitorCommand(cmd => { Log.Information(cmd.CommandText); }) .Build(); Log.Information("freesql builder done!"); var dataTables= fsql.DbFirst.GetTablesByDatabase(" your database "); var doc = new MarkdownDocument(); foreach (var dataTable in dataTables) { doc.Add(new Heading(2, string.Format("{0}({1})", dataTable.Name, dataTable.Comment))); var columTable = new Table(6) { new TableRow { new TableCell("Field"), new TableCell("Type"), new TableCell("Null"), new TableCell("Key"), new TableCell("Default"), new TableCell("Remarks") } }; foreach (var item in dataTable.Columns) { var tableRow = new TableRow{new TableCell(item.Name), new TableCell(item.DbTypeTextFull), new TableCell(item.IsNullable?"是":"否"), new TableCell(item.IsPrimary?"Pri":""), new TableCell(item.DefaultValue), new TableCell(item.Comment) }; columTable.Add(tableRow); } doc.Add(columTable); } using TextWriter writer = File.CreateText("you_table_schema.md"); doc.Write(writer, null);
结尾
这样就可以获取到一个表结构的md文档。

浙公网安备 33010602011771号