Skip to content

Instantly share code, notes, and snippets.

@pdwetz
Last active April 28, 2021 17:30
Show Gist options
  • Save pdwetz/491e8a0478c2e2f7ba0a2acd5839c497 to your computer and use it in GitHub Desktop.
Save pdwetz/491e8a0478c2e2f7ba0a2acd5839c497 to your computer and use it in GitHub Desktop.
Generates a POCO (plain old C# object) based on the table/view schema in SQL Server. Assumes you're already in the correct database and don't need a special schema. Based on the mysql gist (https://gist.github.com/pdwetz/5368441) and MS docs (https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings)
declare @table varchar(50);
set @table = 'TableOrViewName';
select 'public ' + tps.dest
+ (case when IS_NULLABLE = 'YES' and tps.dest != 'string' then '? ' else ' ' end)
+ column_name + ' { get; set; }'
from information_schema.columns c
join (
select 'char' as origin, 'string' as dest union all
select 'varchar', 'string' union all
select 'nvarchar', 'string' union all
select 'text', 'string' union all
select 'ntext', 'string' union all
select 'xml', 'Xml' union all
select 'binary', 'byte[]' union all
select 'timestamp', 'byte[]' union all
select 'uniqueidentifier', 'Guid' union all
select 'date', 'DateTime' union all
select 'datetime', 'DateTime' union all
select 'smalldatetime', 'DateTime' union all
select 'datetime2', 'DateTime' union all
select 'datetimeoffset', 'DateTimeOffset' union all
select 'time', 'TimeSpan' union all
select 'int', 'int' union all
select 'tinyint', 'byte' union all
select 'smallint', 'short' union all
select 'bigint', 'long' union all
select 'decimal', 'decimal' union all
select 'money', 'decimal' union all
select 'smallmoney', 'decimal' union all
select 'numeric', 'decimal' union all
select 'float', 'double' union all
select 'real', 'float' union all
select 'hierarchyid', 'SqlHierarchyId' union all
select 'bit', 'bool'
) tps on c.DATA_TYPE like tps.origin
where table_name = @table
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment