小优化Dapper POCO类别生成器 (自动以表格名称当类别名称)

原版本是作者Necroskillz写的POCO生成器 Generate C# POCOs from SQL statement in LINQPad | NecroNET.org
接着修改版是kevin前辈做的,可以参考前辈的文章 : mrkt 的程式学习笔记: Dapper - 使用 LINQPad 快速产生相对映 SQL Command 查询结果的类别


这次主要增加不用手工修改类别名称,直接拿资料库表格名称来用,想指定名称也保留原版方式
提供给同样想偷懒的读者 :)

逻辑:

ExecuteReader添加CommandBehavior.KeyInfo参数配合GetSchemaTable方法可以额外取得BaseTableName资料增加CommandBehavior.SingleRow只需要取得第一行资料就足够分析产生class的资料

线上测试连结 : POCO Generator | .NET Fiddle

public static class LINQPadExtensions{private static readonly Dictionary<Type, string> TypeAliases = new Dictionary<Type, string> {{ typeof(int), "int" },{ typeof(short), "short" },{ typeof(byte), "byte" },{ typeof(byte[]), "byte[]" },{ typeof(long), "long" },{ typeof(double), "double" },{ typeof(decimal), "decimal" },{ typeof(float), "float" },{ typeof(bool), "bool" },{ typeof(string), "string" }};private static readonly HashSet<Type> NullableTypes = new HashSet<Type> {typeof(int),typeof(short),typeof(long),typeof(double),typeof(decimal),typeof(float),typeof(bool),typeof(DateTime)};public static string DumpClass(this IDbConnection connection, string sql,string className = null){if (connection.State != ConnectionState.Open)connection.Open();var cmd = connection.CreateCommand();cmd.CommandText = sql;var reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SingleRow );var builder = new StringBuilder();do{if (reader.FieldCount <= 1) continue;var schema = reader.GetSchemaTable();foreach (DataRow row in schema.Rows){if (string.IsNullOrWhiteSpace(builder.ToString())){var tableName = string.IsNullOrWhiteSpace(className)?row["BaseTableName"] as string:className;builder.AppendFormat("public class {0}{1}", tableName, Environment.NewLine);builder.AppendLine("{");}var type = (Type)row["DataType"];var name = TypeAliases.ContainsKey(type) ? TypeAliases[type] : type.Name;var isNullable = (bool)row["AllowDBNull"] && NullableTypes.Contains(type);var collumnName = (string)row["ColumnName"];builder.AppendLine(string.Format("\tpublic {0}{1} {2} {{ get; set; }}", name, isNullable ? "?" : string.Empty, collumnName));builder.AppendLine();}builder.AppendLine("}");builder.AppendLine();} while (reader.NextResult());return builder.ToString();}}

使用方式

void Main(){using (IDbConnection connection = Connection){Console.WriteLine(connection.DumpClass("select top 1 * from table"));        /* Result:            public class table            {              public int ID { get; set; }              public string Name { get; set; }            }                */}}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章