NEWS

[SQL SERVER] Chia sẽ hàm convert table sang class C#

[SQL SERVER] Chia sẽ hàm convert table sang class C#
Đăng bởi: Thảo Meo - Lượt xem: 7233 07:37:36, 14/04/2018C#   In bài viết

Bài viết hôm nay, mình sẽ tiếp tục chia sẽ các bạn một hàm trong sqlserver dùng để chuyển một table bất kỳ trong sqlserver thành một class C#.

[SQLSERVER] Convert Table Name to Class C#

Trong lập trình hướng đối tượng C#, các bạn thường tạo ra những Class từ TableName trong database.

Nếu bạn nào đã sử dụng Linq 2 SQL hay Entity Framework thì khi visual studio kết nối với database từ nó sẽ tự động sinh ra cho các bạn các class object tương ứng với những table mà bạn liên kết.

Dưới đây là hàm giúp các bạn có thể dễ dàng chuyển table name sang class:

Ví dụ mình demo bên dưới mình sẽ chuyển table name tbl_user sang class C#

Source code SQL SERVER:

declare @TableName sysname = 'tbl_user'
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

Kết quả trả về khi chạy câu lệnh sql trên:

public class tbl_user
{
    public string tendangnhap { get; set; }

    public string matkhau { get; set; }

    public bool? truycap { get; set; }

    public string sodtgui { get; set; }

    public string nguoitd { get; set; }

    public string thoigian { get; set; }

    public bool? kt { get; set; }

    public int? ma { get; set; }

    public string maphongban { get; set; }

    public string tenphongban { get; set; }

    public int? manv { get; set; }

    public int? nhomuser { get; set; }

    public int? cap { get; set; }

    public bool? morong { get; set; }

    public string avatar { get; set; }

    public string firstname { get; set; }

    public string lastname { get; set; }

    public int id { get; set; }

    public string email { get; set; }

    public bool? online { get; set; }

    public bool? sms { get; set; }

    public bool? duyet { get; set; }

    public string phanhe { get; set; }

    public string groupuser { get; set; }

    public bool? nhanthongbao { get; set; }

    public string vitri { get; set; }

    public string makpi { get; set; }

}

Bonus Create class eXpress Persistent Objects (XPO):

alter PROC sp_create_xpo_class @TableName VARCHAR(50)
as
BEGIN 
SET NOCOUNT ON	
declare @Result varchar(max) = '[Persistent("'+ @TableName +'")]' + CHAR(13) +
+'//[OptimisticLocking(true)]' + CHAR(13) +
'public class ' + @TableName + ': XPLiteObject' + ' 
{' + CHAR(13) +

'    public '+ @TableName + '(Session session) : base(session)
    {
       // session.LockingOption = LockingOption.Optimistic;
    }
'


select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + '_' + ColumnName + '; 
' + 
'
	public ' + ColumnType + NullableSign + ' ' +  ColumnName +'
    {
        get { return '+ '_' + ColumnName +'; }
        set { SetPropertyValue("'+ColumnName +'", ref '+ '_' + ColumnName +', value); }
    }
'
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
END


Kết quả:

[Persistent("tbl_nhanvien_khenthuong")]
//[OptimisticLocking(true)]
public class tbl_nhanvien_khenthuong: XPLiteObject 
{
    public tbl_nhanvien_khenthuong(Session session) : base(session)
    {
       // session.LockingOption = LockingOption.Optimistic;
    }

    public int _id; 

	public int id
    {
        get { return _id; }
        set { SetPropertyValue("id", ref _id, value); }
    }

    public string _manhanvien; 

	public string manhanvien
    {
        get { return _manhanvien; }
        set { SetPropertyValue("manhanvien", ref _manhanvien, value); }
    }

    public string _maphongban; 

	public string maphongban
    {
        get { return _maphongban; }
        set { SetPropertyValue("maphongban", ref _maphongban, value); }
    }

    public string _mabophan; 

	public string mabophan
    {
        get { return _mabophan; }
        set { SetPropertyValue("mabophan", ref _mabophan, value); }
    }

    public string _machucvu; 

	public string machucvu
    {
        get { return _machucvu; }
        set { SetPropertyValue("machucvu", ref _machucvu, value); }
    }

    public DateTime _ngaykhenthuong; 

	public DateTime ngaykhenthuong
    {
        get { return _ngaykhenthuong; }
        set { SetPropertyValue("ngaykhenthuong", ref _ngaykhenthuong, value); }
    }

    public string _sokhenthuong; 

	public string sokhenthuong
    {
        get { return _sokhenthuong; }
        set { SetPropertyValue("sokhenthuong", ref _sokhenthuong, value); }
    }

    public int _sotien; 

	public int sotien
    {
        get { return _sotien; }
        set { SetPropertyValue("sotien", ref _sotien, value); }
    }

    public DateTime _tungay; 

	public DateTime tungay
    {
        get { return _tungay; }
        set { SetPropertyValue("tungay", ref _tungay, value); }
    }

    public DateTime _denngay; 

	public DateTime denngay
    {
        get { return _denngay; }
        set { SetPropertyValue("denngay", ref _denngay, value); }
    }

    public string _hinhthuckhenthuong; 

	public string hinhthuckhenthuong
    {
        get { return _hinhthuckhenthuong; }
        set { SetPropertyValue("hinhthuckhenthuong", ref _hinhthuckhenthuong, value); }
    }

    public string _ghichu; 

	public string ghichu
    {
        get { return _ghichu; }
        set { SetPropertyValue("ghichu", ref _ghichu, value); }
    }

    public string _created_user; 

	public string created_user
    {
        get { return _created_user; }
        set { SetPropertyValue("created_user", ref _created_user, value); }
    }

    public DateTime _created_date; 

	public DateTime created_date
    {
        get { return _created_date; }
        set { SetPropertyValue("created_date", ref _created_date, value); }
    }

    public string _edited_user; 

	public string edited_user
    {
        get { return _edited_user; }
        set { SetPropertyValue("edited_user", ref _edited_user, value); }
    }

    public DateTime _edited_date; 

	public DateTime edited_date
    {
        get { return _edited_date; }
        set { SetPropertyValue("edited_date", ref _edited_date, value); }
    }

}

 

HAVE FUN :)

Tags:

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[SQL SERVER] Chia sẽ hàm convert table sang class C#
Đăng bởi: Thảo Meo - Lượt xem: 7233 07:37:36, 14/04/2018C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.