Skip to content

Instantly share code, notes, and snippets.

@praschl
Created August 24, 2017 13:15
Show Gist options
  • Select an option

  • Save praschl/30a8eeebe886812a1ffe09bfbb5aa81e to your computer and use it in GitHub Desktop.

Select an option

Save praschl/30a8eeebe886812a1ffe09bfbb5aa81e to your computer and use it in GitHub Desktop.
LINQPad Extensions to generate Class and Insert Statements from SQL
// DumpClass: this.Connection.DumpClass("SELECT * from finalpdfpageinfo")
// DumpInsert: this.Connection.DumpInsert("SELECT * from finalpdfpageinfo")
public static class CSharpClassFromSqlGeneratorExtensions
{
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)
{
if(connection.State != ConnectionState.Open)
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText = sql;
using(var reader = cmd.ExecuteReader())
{
var builder = new StringBuilder();
do
{
if(reader.FieldCount <= 1) continue;
builder.AppendLine("public class Info");
builder.AppendLine("{");
var schema = reader.GetSchemaTable();
foreach (DataRow row in schema.Rows)
{
var type = (Type)row["DataType"];
var name = TypeAliases.ContainsKey(type) ? TypeAliases[type] : type.Name;
var isNullable = (bool)row["AllowDBNull"] && NullableTypes.Contains(type);
var columnName = (string)row["ColumnName"];
builder.AppendLine("\t/// <summary>");
builder.AppendLine("\t/// Gets or sets the " + columnName + ".");
builder.AppendLine("\t/// </summary>");
builder.AppendLine(string.Format("\tpublic {0}{1} {2} {{ get; set; }}", name, isNullable ? "?" : string.Empty, columnName));
}
builder.AppendLine("}");
builder.AppendLine();
} while(reader.NextResult());
return builder.ToString();
}
}
public static string DumpInsert(this IDbConnection connection, string sql)
{
if(connection.State != ConnectionState.Open)
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText = sql;
using (var reader = cmd.ExecuteReader())
{
var builder = new StringBuilder();
do
{
if(reader.FieldCount <= 1) continue;
var schema = reader.GetSchemaTable();
var tableName = schema.TableName;
var columnsBuilder = new StringBuilder();
var valuesBuilder = new StringBuilder();
var mapBuilder = new StringBuilder();
foreach (DataRow row in schema.Rows)
{
var columnName = (string)row["ColumnName"];
var lowerColumnName = columnName[0].ToString().ToLower() + columnName.Substring(1);
if (columnsBuilder.Length>0)
{
columnsBuilder.AppendLine(",");
valuesBuilder.AppendLine(",");
mapBuilder.AppendLine(",");
}
columnsBuilder.Append("\t["+columnName+"]");
valuesBuilder.Append("\t@"+lowerColumnName);
mapBuilder.Append("\t"+lowerColumnName + " = entity." + columnName);
}
builder.AppendLine(string.Format("private const string InsertStatement = @\"INSERT INTO [{3}] ({2}{0}) {2}VALUES ({2}{1}{2})\";", columnsBuilder, valuesBuilder,Environment.NewLine, tableName));
builder.AppendLine(string.Format("{0}var insertParameters = new {0}{{{0}{1}{0}}};", Environment.NewLine, mapBuilder));
} while(reader.NextResult());
return builder.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment