In the development process often need to write the corresponding entity class according to the data table, the following is the use of SQL statements to quickly convert the data table to the corresponding entity class code, use only the first line of ' TableName ' quotation marks inside the letter to the specific table name on the line:
Declare @TableNamesysname= 'TableName'Declare @Result varchar(Max)= 'Public class' + @TableName + '{'Select @Result = @Result + ' Public' +ColumnType+Nullablesign+ ' ' +ColumnName+ '{get; set;}' from( Select Replace(Col.name,' ','_') ColumnName, column_id ColumnId, CaseTyp.name when 'bigint' Then 'Long' when 'binary' Then 'byte[]' when 'bit' Then 'BOOL' when 'Char' Then 'string' 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 'string' 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' Else 'Unknown_' +Typ.nameEndColumnType, Case whenCol.is_nullable= 1 andTyp.nameinch('bigint','bit','Date','datetime','datetime2','DateTimeOffset','decimal','float','int',' Money','Numeric','Real','smalldatetime','smallint','smallmoney',' Time','tinyint','uniqueidentifier') Then '?' Else "' Endnullablesign fromsys.columns ColJoinSys.types Typ oncol.system_type_id=typ.system_type_id andcol.user_type_id=typ.user_type_idwhere object_id = object_id(@TableName)) TOrder byColumnIdSet @Result = @Result + '}'Print @Result
Quickly convert data tables to entity classes using SQL statements