如何使用TSQL从数据库中创建EF中的POCO类

时间:2013-10-11 08:41:48

标签: entity-framework

如何使用TSQL从数据库创建EF中的POCO类。

我在SQL-SERVER中创建了可以使用TSQL创建POCO类的存储过程。

1 个答案:

答案 0 :(得分:0)

CREATE PROCEDURE stp_POCO_CLASS_Creator 
    @pTableName VARCHAR(100)
AS

SET NOCOUNT ON
DECLARE @TableDesc VARCHAR(300)
DECLARE @FieldName VARCHAR(100)
DECLARE @FieldDesc VARCHAR(300)
DECLARE @FieldType VARCHAR(20)

DECLARE TableCursor CURSOR LOCAL FORWARD_ONLY
FOR
    SELECT 
        CAST(T5.value AS VARCHAR(300)) AS TableDesc,
        ISNULL(T2.name,'')  AS FieldName,
        ISNULL(CAST(T4.value AS VARCHAR(300)),'') AS FieldDesc,

        CASE T3.name 
            WHEN 'varchar' THEN 'string'
            WHEN 'nvarchar' THEN 'string'
            WHEN 'int' THEN 'int'
            WHEN 'smallint' THEN 'int'
            WHEN 'char' THEN 'string'
            WHEN 'float' THEN 'double'
            WHEN 'bit' THEN 'bool'
            WHEN 'tinyint' THEN 'int'
            WHEN 'bigint' THEN 'Int64'
            WHEN 'decimal' THEN 'Decimal'
            WHEN 'datetime' THEN 'DateTime'
            WHEN 'smalldatetime' THEN 'DateTime'
            WHEN 'real' THEN 'Single'
        END AS  FieldType

    FROM sys.objects T1 INNER JOIN
         sys.columns T2 ON T1.object_id=T2.object_id INNER JOIN
         sys.types T3 ON t2.system_type_id=t3.user_type_id LEFT JOIN
         sys.extended_properties T4 ON T2.object_id=T4.major_id AND T2.column_id=T4.minor_id LEFT JOIN
         sys.extended_properties  T5 ON T1.object_id=T5.major_id AND T5.minor_id=0
     WHERE T1.name= @pTableName


OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @TableDesc,@FieldName,@FieldDesc,@FieldType


PRINT 'using YourProject.Domain.Seedwork.DomainBase;'
PRINT 'using System;'
PRINT 'using System.Collections.Generic;'
PRINT 'using System.Linq;'
PRINT 'using System.Text;'
PRINT 'using System.Threading.Tasks;'
PRINT 'namespace YourProject.Domain.SubsystemName.Models'
PRINT '{'
PRINT ' // ' + @TableDesc
PRINT ' public class '+@pTableName+' : Entity'
PRINT ' {'

WHILE @@FETCH_STATUS=0
BEGIN
    PRINT ' // ' + @FieldDesc
    PRINT ' public '+ @FieldType + ' '+ @FieldName +' { get; set; }' + CHAR(13)
    FETCH NEXT FROM TableCursor INTO @TableDesc,@FieldName,@FieldDesc,@FieldType
END

PRINT ' }'
PRINT '}'

PRINT ' #region IModelConfig Members'
PRINT ' -- Then you must config this class by inherit of IModelConfig and EntityTypeConfiguration<'+@pTableN`enter code here`ame+'>'
PRINT '/*public void RegisterConfig(System.Data.Entity.ModelConfiguration.Configuration.ConfigurationRegistrar registrar)'
PRINT ' {'
PRINT '     registrar.Add(this);'
PRINT ' }*/'
PRINT ' #endregion'

CLOSE TableCursor
DEALLOCATE TableCursor

    enter code here