generate c 23 class from sql server table

Solutions on MaxInterview for generate c 23 class from sql server table by the best coders in the world

showing results for - "generate c 23 class from sql server table"
Guadalupe
02 Apr 2019
1declare @TableName sysname = 'TableName'
2declare @Result varchar(max) = 'public class ' + @TableName + '
3{'
4
5select @Result = @Result + '
6    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
7'
8from
9(
10    select 
11        replace(col.name, ' ', '_') ColumnName,
12        column_id ColumnId,
13        case typ.name 
14            when 'bigint' then 'long'
15            when 'binary' then 'byte[]'
16            when 'bit' then 'bool'
17            when 'char' then 'string'
18            when 'date' then 'DateTime'
19            when 'datetime' then 'DateTime'
20            when 'datetime2' then 'DateTime'
21            when 'datetimeoffset' then 'DateTimeOffset'
22            when 'decimal' then 'decimal'
23            when 'float' then 'double'
24            when 'image' then 'byte[]'
25            when 'int' then 'int'
26            when 'money' then 'decimal'
27            when 'nchar' then 'string'
28            when 'ntext' then 'string'
29            when 'numeric' then 'decimal'
30            when 'nvarchar' then 'string'
31            when 'real' then 'float'
32            when 'smalldatetime' then 'DateTime'
33            when 'smallint' then 'short'
34            when 'smallmoney' then 'decimal'
35            when 'text' then 'string'
36            when 'time' then 'TimeSpan'
37            when 'timestamp' then 'long'
38            when 'tinyint' then 'byte'
39            when 'uniqueidentifier' then 'Guid'
40            when 'varbinary' then 'byte[]'
41            when 'varchar' then 'string'
42            else 'UNKNOWN_' + typ.name
43        end ColumnType,
44        case 
45            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
46            then '?' 
47            else '' 
48        end NullableSign
49    from sys.columns col
50        join sys.types typ on
51            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
52    where object_id = object_id(@TableName)
53) t
54order by ColumnId
55
56set @Result = @Result  + '
57}'
58
59print @Result
60