How to generate model from database using Dapper?

dapper micro-orm visual-studio-2010

Question

I am coming from PetaPoco camp. PetaPoco has a T4 template which generates model from the database. Is anything similar available for Dapper?

I installed Dapper using NuGet and added SqlHelper.cs, but I didn't find anything which generates model from the database.

Accepted Answer

Dapper itself provides few extension methods (Query, Execute) for the connection object and does not have "model generator." Perhaps some other framework can be used to generate POCO's based on the db schema.

Update:

Database tables to C# POCO classes T4 template


Popular Answer

I've just recently written a sql query to do the job for myself. And updating it with extra types when i need. Just replace the table name where it says @@@@.

To make alot of tables i created a temp stored procedure to call. eg. exec createTablePOCO(@tableName)

SELECT 
'public ' + a1.NewType + ' ' + a1.COLUMN_NAME + ' {get;set;}'
,*
 FROM 
(
/*using top because i'm putting an order by ordinal_position on it. 
putting a top on it is the only way for a subquery to be ordered*/
SELECT TOP 100 PERCENT
COLUMN_NAME,
DATA_TYPE,
IS_NULLABLE,
CASE 
    WHEN DATA_TYPE = 'varchar' THEN 'string'
    WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'NO' THEN 'DateTime'
    WHEN DATA_TYPE = 'datetime' AND IS_NULLABLE = 'YES' THEN 'DateTime?'
    WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'YES' THEN 'int?'
    WHEN DATA_TYPE = 'int' AND IS_NULLABLE = 'NO' THEN 'int'
    WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'NO' THEN 'Int16'
    WHEN DATA_TYPE = 'smallint' AND IS_NULLABLE = 'YES' THEN 'Int16?'
    WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'NO' THEN 'decimal'
    WHEN DATA_TYPE = 'decimal' AND IS_NULLABLE = 'YES' THEN 'decimal?'
    WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'NO' THEN 'decimal'
    WHEN DATA_TYPE = 'numeric' AND IS_NULLABLE = 'YES' THEN 'decimal?'
    WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'NO' THEN 'decimal'
    WHEN DATA_TYPE = 'money' AND IS_NULLABLE = 'YES' THEN 'decimal?'
    WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'NO' THEN 'long'
    WHEN DATA_TYPE = 'bigint' AND IS_NULLABLE = 'YES' THEN 'long?'
    WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'NO' THEN 'byte'
    WHEN DATA_TYPE = 'tinyint' AND IS_NULLABLE = 'YES' THEN 'byte?'
    WHEN DATA_TYPE = 'char' THEN 'string'
    WHEN DATA_TYPE = 'timestamp' THEN 'byte[]'
    WHEN DATA_TYPE = 'varbinary' THEN 'byte[]'
    WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'NO' THEN 'bool'
    WHEN DATA_TYPE = 'bit' AND IS_NULLABLE = 'YES' THEN 'bool?'
    WHEN DATA_TYPE = 'xml' THEN 'string'
END AS NewType
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = '@@@@'
ORDER BY ORDINAL_POSITION
) AS a1



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why