sqlserver数据库表生成C#代码实体类型方法

Teloi 每日编程 小工具评论798阅读模式
declare @TableName sysname = 'TABLE_NAME'
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

我只是记录生活,欢迎来到我的博客! 如需转载,请咨询作者同意后,标明作者以及出处,谢谢!
Teloi
  • 本文由 发表于 2022年12月13日 17:52:38
  • 转载请务必保留本文链接:https://blog.teloi.cn/2022/12/13/sqlserver%e6%95%b0%e6%8d%ae%e5%ba%93%e8%a1%a8%e7%94%9f%e6%88%90c%e4%bb%a3%e7%a0%81%e5%ae%9e%e4%bd%93%e7%b1%bb%e5%9e%8b%e6%96%b9%e6%b3%95/
评论  0  访客  0
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: