Advertisement
Guest User

Untitled

a guest
Dec 18th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. public static class LINQPadExtensions
  2. {
  3.     private static readonly Dictionary<Type, string> TypeAliases = new Dictionary<Type, string> {
  4.         { typeof(int), "int" },
  5.         { typeof(short), "short" },
  6.         { typeof(byte), "byte" },
  7.         { typeof(byte[]), "byte[]" },
  8.         { typeof(long), "long" },
  9.         { typeof(double), "double" },
  10.         { typeof(decimal), "decimal" },
  11.         { typeof(float), "float" },
  12.         { typeof(bool), "bool" },
  13.         { typeof(string), "string" }
  14.     };
  15.      
  16.     private static readonly HashSet<Type> NullableTypes = new HashSet<Type> {
  17.         typeof(int),
  18.         typeof(short),
  19.         typeof(long),
  20.         typeof(double),
  21.         typeof(decimal),
  22.         typeof(float),
  23.         typeof(bool),
  24.         typeof(DateTime)
  25.     };
  26.  
  27.     public static string DumpClass(this IDbConnection connection, string sql, string className = "Info")
  28.     {
  29.         if(connection.State != ConnectionState.Open)
  30.         {
  31.    connection.Open();
  32.   }
  33.              
  34.         var cmd = connection.CreateCommand();
  35.         cmd.CommandText = sql;
  36.         var reader = cmd.ExecuteReader();
  37.                          
  38.         var builder = new StringBuilder();
  39.         do
  40.         {
  41.             if(reader.FieldCount <= 1) continue;
  42.          
  43.             builder.AppendFormat("public class {0}{1}", className, Environment.NewLine);
  44.             builder.AppendLine("{");
  45.             var schema = reader.GetSchemaTable();
  46.                          
  47.             foreach (DataRow row in schema.Rows)
  48.             {
  49.                 var type = (Type)row["DataType"];
  50.                 var name = TypeAliases.ContainsKey(type) ? TypeAliases[type] : type.Name;
  51.                 var isNullable = (bool)row["AllowDBNull"] && NullableTypes.Contains(type);
  52.                 var collumnName = (string)row["ColumnName"];
  53.                  
  54.                 builder.AppendLine(string.Format("\tpublic {0}{1} {2} {{ get; set; }}", name, isNullable ? "?" : string.Empty, collumnName));
  55.     builder.AppendLine();
  56.             }
  57.              
  58.             builder.AppendLine("}");
  59.             builder.AppendLine();            
  60.         } while(reader.NextResult());
  61.          
  62.         return builder.ToString();
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement