zoukankan      html  css  js  c++  java
  • 使用Sql语句快速将数据表转换成实体类

    开发过程中经常需要根据数据表编写对应的实体类,下面是使用sql语句快速将数据表转换成对应实体类的代码,使用时只需要将第一行'TableName'引号里面的字母换成具体的表名称就行了:

    declare @TableName sysname = '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,
            case typ.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.name
            end ColumnType,
            case 
                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') 
                then '?' 
                else '' 
            end NullableSign
        from sys.columns col
            join sys.types typ on
                col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
        where object_id = object_id(@TableName)
    ) t
    order by ColumnId
    
    set @Result = @Result  + '
    }'
    
    print @Result
  • 相关阅读:
    内网其他服务器节点连接Mysql数据库很慢的解决方案
    MongoDB分片技术原理和高可用集群配置方案
    Hive事务原理和Datax同步事务表问题解决
    Mysql使用存储过程创建测试数据
    Hive的原生部署方式
    ByteArray的操作总结(复制、打印、位运算)
    句柄
    C# 使用指针将不同值类型赋值到字节数组中
    对象、字节流转换
    ASP.NET Core学习日志1
  • 原文地址:https://www.cnblogs.com/bayes/p/6206297.html
Copyright © 2011-2022 走看看