首页 > 数据库 > mysql教程 > 如何在没有 ORM 的情况下从 SQL Server 表生成 C# 类?

如何在没有 ORM 的情况下从 SQL Server 表生成 C# 类?

Susan Sarandon
发布: 2024-12-21 02:46:09
原创
479 人浏览过

How to Generate C# Classes from SQL Server Tables Without an ORM?

从 SQL Server 表对象生成类

问题:
如何生成表示的简单类SQL Server 表中的实体,而不使用ORM?

解决方案:
以下 SQL 脚本可用于为给定表生成类定义:

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 'double'
            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 'float'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'long'
            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;
登录后复制

示例:
对于名为“Person”且包含“Name”、“Phone”列的表,生成的类将是:

public class Person
{
    public string Name { get; set; }
    public string Phone { get; set; }
}
登录后复制

以上是如何在没有 ORM 的情况下从 SQL Server 表生成 C# 类?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板