【SQL骚操作】SqlServer数据库表生成C# Model实体类SQL语句
2021/8/26 19:06:43
本文主要是介绍【SQL骚操作】SqlServer数据库表生成C# Model实体类SQL语句,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
已知现有表T1
想快速获取cs类结构
/// <summary> /// T1 /// </summary> public class T1 { /// <summary> /// 主键 /// </summary> public int ID { get; set; } /// <summary> /// 姓名 /// </summary> public string NameLijhs { get; set; } }
通过运行下面的sql即可,先配置表名。
declare @TableName sysname = 'T1' declare @Result varchar(max) = ' /// <summary> /// ' + @TableName + ' /// </summary> public class ' + @TableName + ' {' select @Result = @Result + ' /// <summary> /// ' + CONVERT(NVARCHAR(500), ISNULL(ColName, '无')) + ' /// </summary> public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; } ' from ( SELECT replace(col.name, ' ', '_') ColumnName, column_id ColumnId, prop.value ColName, 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 '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' 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 LEFT JOIN sys.extended_properties prop ON col.object_id = prop.major_id AND col.column_id = prop.minor_id where object_id = object_id(@TableName) ) t --order by ColumnId set @Result = @Result + ' }' print @Result
效果如下:
完美,copy到项目里即可。
这篇关于【SQL骚操作】SqlServer数据库表生成C# Model实体类SQL语句的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID