Visualizzazione post con etichetta database. Mostra tutti i post
Visualizzazione post con etichetta database. Mostra tutti i post

2015-01-13

Generate .NET POCO classes from MySQL query

Lately I have been playing a lot with ORMs and Micro-ORMs. Most solutions out there offer a template to create your POCO classes from tables but I did not want to bother with any of them and neither I wanted classes for all tables in my database.

So I came up with a simple solution, based on a straight SQL query, that writes tedious code for you.

(Classes are generated in C#)



SELECT CONCAT('public ',
CASE
 WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'NO' THEN 'int'
 WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'NO' THEN 'short'
  WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'NO' THEN 'short'
  WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'YES' THEN 'long'
   WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'YES' THEN 'int?'
 WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'YES' THEN 'short?'
  WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'YES' THEN 'short?'
  WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'YES' THEN 'long?'
 WHEN DATA_TYPE = 'varchar' THEN 'string'
 WHEN DATA_TYPE = 'date' THEN 'DateTime'
 WHEN DATA_TYPE = 'datetime' THEN 'DateTime'
 WHEN DATA_TYPE = 'decimal' THEN 'decimal'
  WHEN DATA_TYPE = 'char' THEN 'string'
 END,
 ' ', COLUMN_NAME, ' { get; set; }') AS result
 FROM COLUMNS WHERE table_schema LIKE 'your_database_name' AND table_name LIKE 'your_table_name'



Simply replace your_database_name and your_table_name with appropriate names.

QatQat