Wednesday, February 22, 2012

Creating C# Properties with SQL Server Table Schema


declare @TableName sysname = 'WAccessRequests'

declare @result varchar(max) = ''



select @result = @result + '

public ' + ColumnType + ' ' + ColumnName + ' { get; set; }

'

from

(

select replace(col.name, ' ', '_') ColumnName,

case typ.name

when 'bigint' then 'long'

when 'binary' then 'byte[]'

when 'bit' then 'bool'

when 'char' then 'char'

when 'date' then 'DateTime'

when 'datetime' then 'DateTime'

when 'datetime2' then 'DateTime'

when 'datetimeoffset' then 'DateTimeOffset'

when 'decimal' then 'decimal'

when 'float' then 'float'

when 'image' then 'byte[]'

when 'int' then 'int'

when 'money' then 'decimal'

when 'nchar' then 'char'

when 'ntext' then 'string'

when 'numeric' then 'decimal'

when 'nvarchar' then 'string'

when 'real' then 'double'

when 'smalldatetime' then 'DateTime'

when 'smallint' then 'short'

when 'smallmoney' then 'decimal'

when 'text' then 'string'

when 'time' then 'TimeSpan'

when 'timestamp' then 'DateTime'

when 'tinyint' then 'byte'

when 'uniqueidentifier' then 'Guid'

when 'varbinary' then 'byte[]'

when 'varchar' then 'string'

end ColumnType

from sys.columns col

join sys.types typ on

col.system_type_id = typ.system_type_id

where object_id = object_id(@TableName)

)
t



print @result




Output



(17 row(s) affected)



public short AccessRequestID { get; set; }

public short UserCreated { get; set; }

public short UserModified { get; set; }

public int SourceContactID { get; set; }

public DateTime IndividualDateOfBirth { get; set; }

public DateTime RegistrationDate { get; set; }

public DateTime DateCreated { get; set; }

public DateTime DateModified { get; set; }

public bool isRegistered { get; set; }

public bool ValidRequest { get; set; }

public string Num { get; set; }

public string IndividualName { get; set; }

public string ValidNumber { get; set; }

public string IndividualJobTitle { get; set; }

public string IndividualNationality { get; set; }

public string IndividualEmailAddress { get; set; }

public string RegistrationPassword { get; set; }


No comments: