sqlserver表生成C#实体类

新建数据库查询,使用以下代码,记得修改表名称
复制代码
 1 declare @TableName sysname = '表名称'
 2 declare @Result varchar(max) = 'public class ' + @TableName + '
 3 {'
 4 
 5 select @Result = @Result + '
 6     public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
 7 '
 8 from
 9 (
10     select 
11         replace(col.name, ' ', '_') ColumnName,
12         column_id ColumnId,
13         case typ.name 
14             when 'bigint' then 'long'
15             when 'binary' then 'byte[]'
16             when 'bit' then 'bool'
17             when 'char' then 'string'
18             when 'date' then 'DateTime'
19             when 'datetime' then 'DateTime'
20             when 'datetime2' then 'DateTime'
21             when 'datetimeoffset' then 'DateTimeOffset'
22             when 'decimal' then 'decimal'
23             when 'float' then 'double'
24             when 'image' then 'byte[]'
25             when 'int' then 'int'
26             when 'money' then 'decimal'
27             when 'nchar' then 'string'
28             when 'ntext' then 'string'
29             when 'numeric' then 'decimal'
30             when 'nvarchar' then 'string'
31             when 'real' then 'float'
32             when 'smalldatetime' then 'DateTime'
33             when 'smallint' then 'short'
34             when 'smallmoney' then 'decimal'
35             when 'text' then 'string'
36             when 'time' then 'TimeSpan'
37             when 'timestamp' then 'long'
38             when 'tinyint' then 'byte'
39             when 'uniqueidentifier' then 'Guid'
40             when 'varbinary' then 'byte[]'
41             when 'varchar' then 'string'
42             else 'UNKNOWN_' + typ.name
43         end ColumnType,
44         case 
45             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') 
46             then '?' 
47             else '' 
48         end NullableSign
49     from sys.columns col
50         join sys.types typ on
51             col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
52     where object_id = object_id(@TableName)
53 ) t
54 order by ColumnId
55 
56 set @Result = @Result  + '
57 }'
58 
59 print @Result
复制代码

 

posted @   a2151888  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示