using System.Data.SqlClient;
using System.Collections.Generic;
public static void Main()
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
var sql = "select top 1 * from OrderDetails";
Console.WriteLine(connection.DumpClass(sql));
public static class LINQPadExtensions
private static readonly Dictionary<Type, string> TypeAliases = new Dictionary<Type, string> {
{ 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> {
public static string DumpClass(this IDbConnection connection, string sql,string className = null)
if (connection.State != ConnectionState.Open)
var cmd = connection.CreateCommand();
var reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SingleRow );
var builder = new StringBuilder();
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??"Info":className;
builder.AppendFormat("public class {0}{1}", tableName, Environment.NewLine);
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));
} while (reader.NextResult());
return builder.ToString();