Skip to content

Instantly share code, notes, and snippets.

@plaisted
Last active February 18, 2020 00:51
Show Gist options
  • Save plaisted/5c2033726b9ad98d1ba16dcaae5a99db to your computer and use it in GitHub Desktop.
Save plaisted/5c2033726b9ad98d1ba16dcaae5a99db to your computer and use it in GitHub Desktop.
declare @tableName varchar(200)
declare @columnName varchar(200)
declare @propList varchar(MAX)
declare @nullable varchar(50)
declare @datatype varchar(50)
declare @maxlen int
declare @sType varchar(50)
declare @sProperty varchar(200)
set @tableName = 'Jobs'
DECLARE table_cursor CURSOR FOR
SELECT TABLE_NAME
FROM [INFORMATION_SCHEMA].[TABLES] where table_name = @tableName
set @propList = 'private static Dictionary<string,string> fields = new Dictionary<string,string>(StringComparer.InvariantCultureIgnoreCase) { '
OPEN table_cursor
FETCH NEXT FROM table_cursor
INTO @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'public class ' + @tableName + ' {'
DECLARE column_cursor CURSOR FOR
SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, isnull(CHARACTER_MAXIMUM_LENGTH,'-1')
from [INFORMATION_SCHEMA].[COLUMNS]
WHERE [TABLE_NAME] = @tableName
order by [ORDINAL_POSITION]
OPEN column_cursor
FETCH NEXT FROM column_cursor INTO @columnName, @nullable, @datatype, @maxlen
WHILE @@FETCH_STATUS = 0
BEGIN
select @propList = @propList + '["' + @columnName + '"] = "' + @columnName + '",'
-- datatype
select @sType = case @datatype
when 'int' then
case when @nullable = 'YES' then 'Int32?'
else 'Int32'
END
when 'decimal' then
case when @nullable = 'YES' then 'Decimal?'
else 'Decimal'
END
when 'money' then
case when @nullable = 'YES' then 'Decimal?'
else 'Decimal'
END
when 'float' then
case when @nullable = 'YES' then 'double?'
else 'double'
END
when 'char' then 'String'
when 'nchar' then 'String'
when 'varchar' then 'String'
when 'nvarchar' then 'String'
when 'uniqueidentifier' then
case when @nullable = 'YES' then 'Guid?'
else 'Guid'
END
when 'datetime' then
case when @nullable = 'YES' then 'DateTime?'
else 'DateTime'
END
when 'bit' then
case when @nullable = 'YES' then 'Boolean?'
else 'Boolean'
END
else 'String'
END
If (@nullable = 'NO')
PRINT '[Required]'
if (@sType = 'String' and @maxLen <> '-1')
Print '[MaxLength(' + convert(varchar(4),@maxLen) + ')]'
SELECT @sProperty = 'public ' + @sType + ' ' + @columnName + ' { get => GetField<' + @sType + '>("'+ @columnName +'"); set => SetField<' + @sType + '>("'+ @columnName +'", value);}'
PRINT @sProperty
print ''
FETCH NEXT FROM column_cursor INTO @columnName, @nullable, @datatype, @maxlen
END
CLOSE column_cursor
DEALLOCATE column_cursor
print @propList + '};'
print ' [JsonIgnore]'
print '[Computed]'
print 'public override Dictionary<string, string> AllowedPatchFields => fields;'
print '}'
print ''
FETCH NEXT FROM table_cursor
INTO @tableName
END
CLOSE table_cursor
DEALLOCATE table_cursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment