복붙노트

[SQL] 데이터베이스 테이블에서 클래스를 생성

SQL

데이터베이스 테이블에서 클래스를 생성

어떻게 SQL Server 테이블 객체에서 클래스를 생성 할 수 있습니까?

좀 ORM을 사용하는 방법에 대해 이야기하고 있지 않다. 난 그냥 엔티티 (단순 클래스)를 작성해야합니다. 뭔가 같은 :

    public class Person 
    {
        public string Name { get;set; }
        public string Phone { get;set; }
    }

일부 테이블 등을 감안할 때 :

+----+-------+----------------+
| ID | Name  |     Phone      |
+----+-------+----------------+
|  1 | Alice | (555) 555-5550 |
|  2 | Bob   | (555) 555-5551 |
|  3 | Cathy | (555) 555-5552 |
+----+-------+----------------+


해결법

  1. ==============================

    1.테이블의 이름으로 설정 @tablename.

    테이블의 이름으로 설정 @tablename.

    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
    
  2. ==============================

    2.난은 SQL Server 2008 R2에 대한 작업에 알렉스의 답변을 얻을 수 없었다. 그래서, 동일한 기본 원칙을 사용하여 다시 썼다. 스키마와 몇 가지 수정이 (널 (NULL) C 번호 값 유형에 널 (NULL) 날짜 형식을 매핑 포함) 열 속성 매핑에 대한되었습니다 위해 지금 할 수 있습니다. 여기에 SQL은 다음과 같습니다

    난은 SQL Server 2008 R2에 대한 작업에 알렉스의 답변을 얻을 수 없었다. 그래서, 동일한 기본 원칙을 사용하여 다시 썼다. 스키마와 몇 가지 수정이 (널 (NULL) C 번호 값 유형에 널 (NULL) 날짜 형식을 매핑 포함) 열 속성 매핑에 대한되었습니다 위해 지금 할 수 있습니다. 여기에 SQL은 다음과 같습니다

       DECLARE @TableName VARCHAR(MAX) = 'NewsItem' -- Replace 'NewsItem' with your table name
        DECLARE @TableSchema VARCHAR(MAX) = 'Markets' -- Replace 'Markets' with your schema name
        DECLARE @result varchar(max) = ''
    
        SET @result = @result + 'using System;' + CHAR(13) + CHAR(13) 
    
        IF (@TableSchema IS NOT NULL) 
        BEGIN
            SET @result = @result + 'namespace ' + @TableSchema  + CHAR(13) + '{' + CHAR(13) 
        END
    
        SET @result = @result + 'public class ' + @TableName + CHAR(13) + '{' + CHAR(13) 
    
        SET @result = @result + '#region Instance Properties' + CHAR(13)  
    
       SELECT
          @result = @result + CHAR(13)
          + ' public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13)
        FROM (SELECT
          c.COLUMN_NAME AS ColumnName,
          CASE c.DATA_TYPE
            WHEN 'bigint' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'Int64?'
                ELSE 'Int64'
              END
            WHEN 'binary' THEN 'Byte[]'
            WHEN 'bit' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'bool?'
                ELSE 'bool'
              END
            WHEN 'char' THEN 'string'
            WHEN 'date' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'DateTime?'
                ELSE 'DateTime'
              END
            WHEN 'datetime' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'DateTime?'
                ELSE 'DateTime'
              END
            WHEN 'datetime2' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'DateTime?'
                ELSE 'DateTime'
              END
            WHEN 'datetimeoffset' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'DateTimeOffset?'
                ELSE 'DateTimeOffset'
              END
            WHEN 'decimal' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'decimal?'
                ELSE 'decimal'
              END
            WHEN 'float' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'Single?'
                ELSE 'Single'
              END
            WHEN 'image' THEN 'Byte[]'
            WHEN 'int' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'int?'
                ELSE 'int'
              END
            WHEN 'money' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'decimal?'
                ELSE 'decimal'
              END
            WHEN 'nchar' THEN 'string'
            WHEN 'ntext' THEN 'string'
            WHEN 'numeric' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'decimal?'
                ELSE 'decimal'
              END
            WHEN 'nvarchar' THEN 'string'
            WHEN 'real' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'Double?'
                ELSE 'Double'
              END
            WHEN 'smalldatetime' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'DateTime?'
                ELSE 'DateTime'
              END
            WHEN 'smallint' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'Int16?'
                ELSE 'Int16'
              END
            WHEN 'smallmoney' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'decimal?'
                ELSE 'decimal'
              END
            WHEN 'text' THEN 'string'
            WHEN 'time' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'TimeSpan?'
                ELSE 'TimeSpan'
              END
            WHEN 'timestamp' THEN 'Byte[]'
            WHEN 'tinyint' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'Byte?'
                ELSE 'Byte'
              END
            WHEN 'uniqueidentifier' THEN CASE C.IS_NULLABLE
                WHEN 'YES' THEN 'Guid?'
                ELSE 'Guid'
              END
            WHEN 'varbinary' THEN 'Byte[]'
            WHEN 'varchar' THEN 'string'
            ELSE 'Object'
          END AS ColumnType,
          c.ORDINAL_POSITION
        FROM INFORMATION_SCHEMA.COLUMNS c
        WHERE c.TABLE_NAME = @TableName
        AND ISNULL(@TableSchema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA) t
        ORDER BY t.ORDINAL_POSITION
    
        SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)  
    
        SET @result = @result  + '}' + CHAR(13)
    
        IF (@TableSchema IS NOT NULL) 
        BEGIN
            SET @result = @result + CHAR(13) + '}' 
        END
    
        PRINT @result
    

    그것은 다음과 같은 C 번호를 생성합니다 :

    using System;
    
    namespace Markets
    {
        public class NewsItem        {
            #region Instance Properties
    
            public Int32 NewsItemID { get; set; }
    
            public Int32? TextID { get; set; }
    
            public String Description { get; set; }
    
            #endregion Instance Properties
        }
    
    }
    

    SQL로 EF, Linq에를 사용하는 아이디어, 또는 목재 될 수있다; 다음과 같이 코딩의 조각이 편리 할 때가 있습니다. 솔직히, 나는 코드가 1000 행 그리드를 채우는 19,200 별도의 데이터베이스 호출을 만들어 생성 EF 탐색 속성을 사용하여 좋아하지 않는다. 이것은 하나의 데이터베이스 호출에 달성 될 수 있었다. 그럼에도 불구하고, 단지 기술적 인 건축가가 당신이 좋아하는 EF와를 사용하지 않습니다 수 있습니다. 그래서, 당신은 ... 같은 코드로 되돌릴 덧붙여, 또한 등 DataAnnotations에 대한 속성과 각 속성을 장식하는 생각이 될 수있다, 그러나 나는 엄격하게 POCO을이을 유지하고있다.

    편집하다 타임 스탬프와 가이 드에 대한 고정?

  3. ==============================

    3.VB 버전

    VB 버전

    declare @TableName sysname = 'myTableName'
    declare @prop varchar(max)
    PRINT 'Public Class ' + @TableName
    declare props cursor for
    select distinct ' public property ' + ColumnName + ' AS ' + ColumnType AS prop
    from ( 
        select  
            replace(col.name, ' ', '_') ColumnName,  column_id, 
            case typ.name  
                when 'bigint' then 'long' 
                when 'binary' then 'byte[]' 
                when 'bit' then 'boolean' 
                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 'integer' 
                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' 
            end ColumnType 
        from sys.columns col join sys.types typ on col.system_type_id = typ.system_type_id 
        where object_id = object_id(@TableName) 
    ) t 
    order by prop
    open props
    FETCH NEXT FROM props INTO @prop
    WHILE @@FETCH_STATUS = 0
    BEGIN
        print @prop
        FETCH NEXT FROM props INTO @prop
    END
    close props
    DEALLOCATE props
    PRINT 'End Class'
    
  4. ==============================

    4.A는 후반 비트하지만 난 도움에 대한 웹 도구는 C 번호를 생성 생성 (또는 다른) 한 SQL 결과, SQL 테이블 및 SQL SP에서 객체.

    A는 후반 비트하지만 난 도움에 대한 웹 도구는 C 번호를 생성 생성 (또는 다른) 한 SQL 결과, SQL 테이블 및 SQL SP에서 객체.

    sql2object.com

    이것은 귀하의 모든 특성과 유형을 입력 정말 안전 가지고 있습니다.

    종류가 인식되지 않는 경우 기본값은 선택됩니다.

  5. ==============================

    5.내 2 센트를 제공하기 위해 노력하고있어

    내 2 센트를 제공하기 위해 노력하고있어

    0) QueryFirst https://marketplace.visualstudio.com/items?itemName=bbsimonbb.QueryFirst 쿼리는 최초의 C # 프로젝트에서 SQL 지능적으로 작업을위한 비주얼 스튜디오의 확장입니다. 쿼리를 개발하기 위해 제공 .SQL 템플릿을 사용합니다. 이 파일 저장, 쿼리-먼저 쿼리를 실행하면 스키마를 검색하고 두 개의 클래스와 인터페이스 생성 방법과 래퍼 클래스 () ExecuteScalar는 (), ExecuteNonQuery는을 (실행) 등의 해당 인터페이스 및 POCO의 캡슐화를 결과의 선.

    1) Sql2Objects (그러나 DAL) 쿼리의 결과에서 시작하여 클래스를 생성

    2) https://docs.microsoft.com/en-us/ef/ef6/resources/tools

    3) https://visualstudiomagazine.com/articles/2012/12/11/sqlqueryresults-code-generation.aspx

    4) http://www.codesmithtools.com/product/generator#features

  6. ==============================

    6.당신이 단정 한 같은 간단한 ORM을 사용하는 경우 네 다음은 중대하다.

    당신이 단정 한 같은 간단한 ORM을 사용하는 경우 네 다음은 중대하다.

    당신의 닷넷을 사용하는 경우 WriteXmlSchema 메서드를 사용하여 모든 데이터 집합으로 런타임에 XSD 파일을 생성 할 수 있습니다. http://msdn.microsoft.com/en-us/library/xt7k72x8(v=vs.110).aspx

    이 같이 :

    using (SqlConnection cnn = new SqlConnection(mConnStr)) {
    DataSet Data = new DataSet();
    cnn.Open();
    string sql = "SELECT * FROM Person";
    
    using (SqlDataAdapter Da = new SqlDataAdapter(sql, cnn))
    {
    try
    {
        Da.Fill(Data);
        Da.TableMappings.Add("Table", "Person");
        Data.WriteXmlSchema(@"C:\Person.xsd");
    }
    catch (Exception ex)
    { MessageBox.Show(ex.Message); }
    }
    cnn.Close();
    

    당신은 프롬프트 개발자 명령에서 XML의 직렬화의 클래스를 만들 xsd.exe가 사용할 수 있습니다에서. http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs.110).aspx

    이 같은 :

    xsd C:\Person.xsd /classes /language:CS
    
  7. ==============================

    7.NULLABLE 특성을 인쇄하려면 다음을 사용합니다. 그것은 CASE 문 블록 알렉스 아자의 스크립트에 약간의 수정을 추가합니다.

    NULLABLE 특성을 인쇄하려면 다음을 사용합니다. 그것은 CASE 문 블록 알렉스 아자의 스크립트에 약간의 수정을 추가합니다.

    declare @TableName sysname = 'TableName'
    declare @result varchar(max) = 'public class ' + @TableName + '
    {'
    
    select @result = @result + '
        public ' + ColumnType + ' ' + ColumnName + ' { get; set; }
    '
    from
    (
        select 
            replace(col.name, ' ', '_') ColumnName,
            column_id,
            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 + 
            CASE
                WHEN col.is_nullable=1 AND
                     typ.name NOT IN (
                         'binary', 'varbinary', 'image',
                         'text', 'ntext',
                         'varchar', 'nvarchar', 'char', 'nchar')
                THEN '?'
                ELSE '' END AS [ColumnType]
        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 column_id
    
    set @result = @result  + '
    }'
    
    print @result
    
  8. ==============================

    8.나는 위이 글의 솔루션에 개선 과정에서 제안을 사용하려고했습니다.

    나는 위이 글의 솔루션에 개선 과정에서 제안을 사용하려고했습니다.

    하자 우리는 구현하여 PropertyChanged 이벤트, 당신은 같은 것을 할 것 (이 경우 ObservableObject) 기본 클래스를 사용 말한다. 나는 아마 내 블로그에 어느 날 블로그 게시물을 작성합니다 sqljana.wordpress.com

    처음 세 변수의 값을 대체 할하십시오 :

        --These three things have to be substituted (when called from Powershell, they are replaced before execution)
    DECLARE @Schema VARCHAR(MAX) = N'&Schema'
    DECLARE @TableName VARCHAR(MAX) = N'&TableName'
    DECLARE @Namespace VARCHAR(MAX) = N'&Namespace'
    
    DECLARE @CRLF VARCHAR(2) = CHAR(13) + CHAR(10);
    DECLARE @result VARCHAR(max) = ' '
    
    DECLARE @PrivateProp VARCHAR(100) = @CRLF + 
                    CHAR(9) + CHAR(9) + 'private <ColumnType> _<ColumnName>;';
    DECLARE @PublicProp VARCHAR(255) = @CRLF + 
                    CHAR(9) + CHAR(9) + 'public <ColumnType> <ColumnName> '  + @CRLF +
                    CHAR(9) + CHAR(9) + '{ ' + @CRLF +
                    CHAR(9) + CHAR(9) + '   get { return _<ColumnName>; } ' + @CRLF +
                    CHAR(9) + CHAR(9) + '   set ' + @CRLF +
                    CHAR(9) + CHAR(9) + '   { ' + @CRLF +
                    CHAR(9) + CHAR(9) + '       _<ColumnName> = value;' + @CRLF +
                    CHAR(9) + CHAR(9) + '       base.RaisePropertyChanged();' + @CRLF +
                    CHAR(9) + CHAR(9) + '   } ' + @CRLF +
                    CHAR(9) + CHAR(9) + '}' + @CRLF;
    
    DECLARE @RPCProc VARCHAR(MAX) = @CRLF +         
                    CHAR(9) + CHAR(9) + 'public event PropertyChangedEventHandler PropertyChanged; ' + @CRLF +
                    CHAR(9) + CHAR(9) + 'private void RaisePropertyChanged( ' + @CRLF +
                    CHAR(9) + CHAR(9) + '       [CallerMemberName] string caller = "" ) ' + @CRLF +
                    CHAR(9) + CHAR(9) + '{  ' + @CRLF +
                    CHAR(9) + CHAR(9) + '   if (PropertyChanged != null)  ' + @CRLF +
                    CHAR(9) + CHAR(9) + '   { ' + @CRLF +
                    CHAR(9) + CHAR(9) + '       PropertyChanged( this, new PropertyChangedEventArgs( caller ) );  ' + @CRLF +
                    CHAR(9) + CHAR(9) + '   } ' + @CRLF +
                    CHAR(9) + CHAR(9) + '}';
    
    DECLARE @PropChanged VARCHAR(200) =  @CRLF +            
                    CHAR(9) + CHAR(9) + 'protected override void AfterPropertyChanged(string propertyName) ' + @CRLF +
                    CHAR(9) + CHAR(9) + '{ ' + @CRLF +
                    CHAR(9) + CHAR(9) + '   System.Diagnostics.Debug.WriteLine("' + @TableName + ' property changed: " + propertyName); ' + @CRLF +
                    CHAR(9) + CHAR(9) + '}';
    
    SET @result = 'using System;' + @CRLF + @CRLF +
                    'using MyCompany.Business;' + @CRLF + @CRLF +
                    'namespace ' + @Namespace  + @CRLF + '{' + @CRLF +
                    '   public class ' + @TableName + ' : ObservableObject' + @CRLF + 
                    '   {' + @CRLF +
                    '   #region Instance Properties' + @CRLF 
    
    SELECT @result = @result
                     + 
                    REPLACE(
                                REPLACE(@PrivateProp
                                , '<ColumnName>', ColumnName)
                            , '<ColumnType>', ColumnType)
                    +                           
                    REPLACE(
                                REPLACE(@PublicProp
                                , '<ColumnName>', ColumnName)
                            , '<ColumnType>', ColumnType)                   
    FROM
    (
        SELECT  c.COLUMN_NAME   AS ColumnName 
            , CASE c.DATA_TYPE   
                WHEN 'bigint' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
                WHEN 'binary' THEN 'Byte[]'
                WHEN 'bit' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END            
                WHEN 'char' THEN 'String'
                WHEN 'date' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
                WHEN 'datetime' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
                WHEN 'datetime2' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
                WHEN 'datetimeoffset' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END                                    
                WHEN 'decimal' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                    
                WHEN 'float' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Single?' ELSE 'Single' END                                    
                WHEN 'image' THEN 'Byte[]'
                WHEN 'int' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
                WHEN 'money' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                
                WHEN 'nchar' THEN 'String'
                WHEN 'ntext' THEN 'String'
                WHEN 'numeric' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                            
                WHEN 'nvarchar' THEN 'String'
                WHEN 'real' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Double?' ELSE 'Double' END                                                                        
                WHEN 'smalldatetime' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
                WHEN 'smallint' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END            
                WHEN 'smallmoney' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                                        
                WHEN 'text' THEN 'String'
                WHEN 'time' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END                                                                                    
                WHEN 'timestamp' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
                WHEN 'tinyint' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END                                                
                WHEN 'uniqueidentifier' THEN 'Guid'
                WHEN 'varbinary' THEN 'Byte[]'
                WHEN 'varchar' THEN 'String'
                ELSE 'Object'
            END AS ColumnType
            , c.ORDINAL_POSITION 
    FROM    INFORMATION_SCHEMA.COLUMNS c
    WHERE   c.TABLE_NAME = @TableName 
        AND ISNULL(@Schema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA  
    ) t
    ORDER BY t.ORDINAL_POSITION
    
    SELECT @result = @result + @CRLF + 
                    CHAR(9) + '#endregion Instance Properties' + @CRLF +
                    --CHAR(9) + @RPCProc + @CRLF +
                    CHAR(9) + @PropChanged + @CRLF +
                    CHAR(9) + '}' + @CRLF +
                    @CRLF + '}' 
    --SELECT @result
    PRINT @result
    

    기본 클래스는 여기 조쉬 스미스의 기사에 기반 http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/에서

    나는 ObservableObject 호출 할 클래스의 이름을 변경했고, 또한 CallerMemberName 속성을 사용하여 C # 5 기능을 이용했다

    //From http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/
    //
    //Jana's change: Used c# 5 feature to bypass passing in the property name using [CallerMemberName] 
    //  protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    
    namespace MyCompany.Business
    {
    
        /// <summary>
        /// Implements the INotifyPropertyChanged interface and 
        /// exposes a RaisePropertyChanged method for derived 
        /// classes to raise the PropertyChange event.  The event 
        /// arguments created by this class are cached to prevent 
        /// managed heap fragmentation.
        /// </summary>
        [Serializable]
        public abstract class ObservableObject : INotifyPropertyChanged
        {
            #region Data
    
            private static readonly Dictionary<string, PropertyChangedEventArgs> eventArgCache;
            private const string ERROR_MSG = "{0} is not a public property of {1}";
    
            #endregion // Data
    
            #region Constructors
    
            static ObservableObject()
            {
                eventArgCache = new Dictionary<string, PropertyChangedEventArgs>();
            }
    
            protected ObservableObject()
            {
            }
    
            #endregion // Constructors
    
            #region Public Members
    
            /// <summary>
            /// Raised when a public property of this object is set.
            /// </summary>
            [field: NonSerialized]
            public event PropertyChangedEventHandler PropertyChanged;
    
            /// <summary>
            /// Returns an instance of PropertyChangedEventArgs for 
            /// the specified property name.
            /// </summary>
            /// <param name="propertyName">
            /// The name of the property to create event args for.
            /// </param>        
            public static PropertyChangedEventArgs
                GetPropertyChangedEventArgs(string propertyName)
            {
                if (String.IsNullOrEmpty(propertyName))
                    throw new ArgumentException(
                        "propertyName cannot be null or empty.");
    
                PropertyChangedEventArgs args;
    
                // Get the event args from the cache, creating them
                // and adding to the cache if necessary.
                lock (typeof(ObservableObject))
                {
                    bool isCached = eventArgCache.ContainsKey(propertyName);
                    if (!isCached)
                    {
                        eventArgCache.Add(
                            propertyName,
                            new PropertyChangedEventArgs(propertyName));
                    }
    
                    args = eventArgCache[propertyName];
                }
    
                return args;
            }
    
            #endregion // Public Members
    
            #region Protected Members
    
            /// <summary>
            /// Derived classes can override this method to
            /// execute logic after a property is set. The 
            /// base implementation does nothing.
            /// </summary>
            /// <param name="propertyName">
            /// The property which was changed.
            /// </param>
            protected virtual void AfterPropertyChanged(string propertyName)
            {
            }
    
            /// <summary>
            /// Attempts to raise the PropertyChanged event, and 
            /// invokes the virtual AfterPropertyChanged method, 
            /// regardless of whether the event was raised or not.
            /// </summary>
            /// <param name="propertyName">
            /// The property which was changed.
            /// </param>
            protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
            {
                this.VerifyProperty(propertyName);
    
                PropertyChangedEventHandler handler = this.PropertyChanged;
                if (handler != null)
                {
                    // Get the cached event args.
                    PropertyChangedEventArgs args =
                        GetPropertyChangedEventArgs(propertyName);
    
                    // Raise the PropertyChanged event.
                    handler(this, args);
                }
    
                this.AfterPropertyChanged(propertyName);
            }
    
            #endregion // Protected Members
    
            #region Private Helpers
    
            [Conditional("DEBUG")]
            private void VerifyProperty(string propertyName)
            {
                Type type = this.GetType();
    
                // Look for a public property with the specified name.
                PropertyInfo propInfo = type.GetProperty(propertyName);
    
                if (propInfo == null)
                {
                    // The property could not be found,
                    // so alert the developer of the problem.
    
                    string msg = string.Format(
                        ERROR_MSG,
                        propertyName,
                        type.FullName);
    
                    Debug.Fail(msg);
                }
            }
    
            #endregion // Private Helpers
        }
    }
    

    여기 너희들이 좀 더 좋아하려고하는 부분이다. 나는 SQL 데이터베이스의 모든 테이블에 대해 생성하는 PowerShell 스크립트를 만들었습니다. 그것은 여기에서 다운로드 할 수 있습니다 차드 밀러의 호출 - SQLCmd2 cmdlet에라는 이름의 파워 쉘 전문가에 기초한다 : http://gallery.technet.microsoft.com/ScriptCenter/7985b7ef-ed89-4dfd-b02a-433cc4e30894/

    당신이 cmdlet을 갖게되면, 모든 테이블에 대해 생성 할 수있는 PowerShell 스크립트는 간단한 (특정 값으로 변수를 대체 할)가된다.

    . C:\MyScripts\Invoke-Sqlcmd2.ps1
    
    $serverInstance = "MySQLInstance"
    $databaseName = "MyDb"
    $generatorSQLFile = "C:\MyScripts\ModelGen.sql" 
    $tableListSQL = "SELECT name FROM $databaseName.sys.tables"
    $outputFolder = "C:\MyScripts\Output\"
    $namespace = "MyCompany.Business"
    
    $placeHolderSchema = "&Schema"
    $placeHolderTableName = "&TableName"
    $placeHolderNamespace = "&Namespace"
    
    #Get the list of tables in the database to generate c# models for
    $tables = Invoke-Sqlcmd2 -ServerInstance $serverInstance -Database $databaseName -Query $tableListSQL -As DataRow -Verbose
    
    foreach ($table in $tables)
    {
        $table1 = $table[0]
        $outputFile = "$outputFolder\$table1.cs"
    
    
        #Replace variables with values (returns an array that we convert to a string to use as query)
        $generatorSQLFileWSubstitutions = (Get-Content $generatorSQLFile).
                                                Replace($placeHolderSchema,"dbo").
                                                Replace($placeHolderTableName, $table1).
                                                Replace($placeHolderNamespace, $namespace) | Out-String
    
        "Ouputing for $table1 to $outputFile"
    
        #The command generates .cs file content for model using "PRINT" statements which then gets written to verbose output (stream 4)
        # ...capture the verbose output and redirect to a file
        (Invoke-Sqlcmd2 -ServerInstance $serverInstance -Database $databaseName -Query $generatorSQLFileWSubstitutions -Verbose) 4> $outputFile
    
    }
    
  9. ==============================

    9.당신은 SQL 서버 2016에 액세스 할 수있는 경우, 당신은 선택 문에서 JSON 출력을 얻기 위해에 대한 JSON (와 INCLUDE_NULL_VALUES) 옵션을 사용할 수 있습니다. 출력은 다음 Visual Studio에서, 특수 붙여 복사 -> 클래스로 JSON을 붙여 넣습니다.

    당신은 SQL 서버 2016에 액세스 할 수있는 경우, 당신은 선택 문에서 JSON 출력을 얻기 위해에 대한 JSON (와 INCLUDE_NULL_VALUES) 옵션을 사용할 수 있습니다. 출력은 다음 Visual Studio에서, 특수 붙여 복사 -> 클래스로 JSON을 붙여 넣습니다.

    예산 솔루션의 종류,하지만 약간의 시간을 절약 할 수 있습니다.

  10. ==============================

    10.템플릿을 사용하여 사용자 지정 코드를 작성하기위한 절차를 작성

    템플릿을 사용하여 사용자 지정 코드를 작성하기위한 절차를 작성

    create PROCEDURE [dbo].[createCode]
    (   
       @TableName sysname = '',
       @befor varchar(max)='public class  @TableName  
    {',
       @templet varchar(max)=' 
         public @ColumnType @ColumnName   { get; set; }  // @ColumnDesc  ',
       @after varchar(max)='
    }'
    
    )
    AS
    BEGIN 
    
    
    declare @result varchar(max)
    
    set @befor =replace(@befor,'@TableName',@TableName)
    
    set @result=@befor
    
    select @result = @result 
    + replace(replace(replace(replace(replace(@templet,'@ColumnType',ColumnType) ,'@ColumnName',ColumnName) ,'@ColumnDesc',ColumnDesc),'@ISPK',ISPK),'@max_length',max_length)
    
    from  
    (
        select 
        column_id,
        replace(col.name, ' ', '_') ColumnName,
        typ.name as sqltype,
        typ.max_length,
        is_identity,
        pkk.ISPK, 
            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 + CASE WHEN col.is_nullable=1 AND typ.name NOT IN ('binary', 'varbinary', 'image', 'text', 'ntext', 'varchar', 'nvarchar', 'char', 'nchar') THEN '?' ELSE '' END ColumnType,
          isnull(colDesc.colDesc,'') AS ColumnDesc 
        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
                (
                    SELECT c.name  AS 'ColumnName', CASE WHEN dd.pk IS NULL THEN 'false' ELSE 'true' END ISPK           
                    FROM        sys.columns c
                        JOIN    sys.tables  t   ON c.object_id = t.object_id    
                        LEFT JOIN (SELECT   K.COLUMN_NAME , C.CONSTRAINT_TYPE as pk  
                            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K 
                                LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                            ON K.TABLE_NAME = C.TABLE_NAME
                                AND K.CONSTRAINT_NAME = C.CONSTRAINT_NAME
                                AND K.CONSTRAINT_CATALOG = C.CONSTRAINT_CATALOG
                                AND K.CONSTRAINT_SCHEMA = C.CONSTRAINT_SCHEMA            
                            WHERE K.TABLE_NAME = @TableName) as dd
                         ON dd.COLUMN_NAME = c.name
                     WHERE       t.name = @TableName       
                ) pkk  on ColumnName=col.name
    
        OUTER APPLY (
        SELECT TOP 1 CAST(value AS NVARCHAR(max)) AS colDesc
        FROM
           sys.extended_properties
        WHERE
           major_id = col.object_id
           AND
           minor_id = COLUMNPROPERTY(major_id, col.name, 'ColumnId')
        ) colDesc      
        where object_id = object_id(@TableName)
    
        ) t
    
        set @result=@result+@after
    
        select @result
        --print @result
    
    END
    

    이제 사용자 지정 코드를 만들

    예를 들어 C # 클래스에 대한

    exec [createCode] @TableName='book',@templet =' 
         public @ColumnType @ColumnName   { get; set; }  // @ColumnDesc  '
    

    출력은

    public class  book  
    { 
         public long ID   { get; set; }  //    
         public String Title   { get; set; }  // Book Title  
    }
    

    LINQ에 대한

    exec [createCode] @TableName='book'
    , @befor  ='[System.Data.Linq.Mapping.Table(Name = "@TableName")]
    public class @TableName
    {',
    
       @templet  =' 
         [System.Data.Linq.Mapping.Column(Name = "@ColumnName", IsPrimaryKey = @ISPK)]
         public @ColumnType @ColumnName   { get; set; }  // @ColumnDesc  
         ' ,
    
       @after  ='
    }'
    

    출력은

    [System.Data.Linq.Mapping.Table(Name = "book")]
    public class book
    { 
         [System.Data.Linq.Mapping.Column(Name = "ID", IsPrimaryKey = true)]
         public long ID   { get; set; }  //   
    
         [System.Data.Linq.Mapping.Column(Name = "Title", IsPrimaryKey = false)]
         public String Title   { get; set; }  // Book Title  
    
    }
    

    자바 클래스

    exec [createCode] @TableName='book',@templet =' 
         public @ColumnType @ColumnName ; // @ColumnDesc  
         public @ColumnType get@ColumnName()
         {
            return this.@ColumnName;
         }
         public void set@ColumnName(@ColumnType @ColumnName)
         {
            this.@ColumnName=@ColumnName;
         }
    
         '
    

    출력은

    public class  book  
    { 
         public long ID ; //   
         public long getID()
         {
            return this.ID;
         }
         public void setID(long ID)
         {
            this.ID=ID;
         }
    
    
         public String Title ; // Book Title  
         public String getTitle()
         {
            return this.Title;
         }
         public void setTitle(String Title)
         {
            this.Title=Title;
         } 
    }
    

    안드로이드 설탕 ORM 모델

    exec [createCode] @TableName='book'
    , @befor  ='@Table(name = "@TableName")
    public class @TableName
    {',
       @templet  =' 
         @Column(name = "@ColumnName")
         public @ColumnType @ColumnName ;// @ColumnDesc  
         ' ,
       @after  ='
    }'
    

    출력은

    @Table(name = "book")
    public class book
    { 
         @Column(name = "ID")
         public long ID ;//   
    
         @Column(name = "Title")
         public String Title ;// Book Title  
    
    }
    
  11. ==============================

    11.댓글 (요약)를 NULLABLE 특성을 인쇄하려면 다음을 사용합니다. 그것은 첫 번째 대답에 약간의 수정입니다

    댓글 (요약)를 NULLABLE 특성을 인쇄하려면 다음을 사용합니다. 그것은 첫 번째 대답에 약간의 수정입니다

    declare @TableName sysname = 'TableName'
    declare @result varchar(max) = 'public class ' + @TableName + '
    {'
    select @result = @result 
    + CASE WHEN ColumnDesc IS NOT NULL THEN '
        /// <summary>
        /// ' + ColumnDesc + '
        /// </summary>' ELSE '' END
    + '
        public ' + ColumnType + ' ' + ColumnName + ' { get; set; }'
    from
    (
        select 
            replace(col.name, ' ', '_') ColumnName,
            column_id,
            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 + CASE WHEN col.is_nullable=1 AND typ.name NOT IN ('binary', 'varbinary', 'image', 'text', 'ntext', 'varchar', 'nvarchar', 'char', 'nchar') THEN '?' ELSE '' END ColumnType,
            colDesc.colDesc AS ColumnDesc
        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
        OUTER APPLY (
        SELECT TOP 1 CAST(value AS NVARCHAR(max)) AS colDesc
        FROM
           sys.extended_properties
        WHERE
           major_id = col.object_id
           AND
           minor_id = COLUMNPROPERTY(major_id, col.name, 'ColumnId')
        ) colDesc            
        where object_id = object_id(@TableName)
    ) t
    order by column_id
    
    set @result = @result  + '
    }'
    
    print @result
    
  12. ==============================

    12.비주얼 스튜디오 매거진이 출판 :

    비주얼 스튜디오 매거진이 출판 :

    SQL 쿼리 결과에 대한 생성 .NET POCO 클래스

    그것은 당신이 구축 그것에게 당신의 SQL 정보를주고, 당신의 클래스를 크랭크 할 수있는 다운로드 할 수있는 프로젝트를 가지고있다.

    이제 도구는 .... SELECT, INSERT 및 UPDATE에 대한 SQL 명령을 만든 경우

  13. ==============================

    13.http://www.codesmithtools.com/product/generator : 상용,하지만 CodeSmith 발전기는 않습니다

    http://www.codesmithtools.com/product/generator : 상용,하지만 CodeSmith 발전기는 않습니다

  14. ==============================

    14.난 당신이 밖으로 원하는 무엇을 혼동하고 있습니다 만, 여기 당신이 디자인 할 것을 설계 할 때 일반적으로 옵션이 있습니다.

    난 당신이 밖으로 원하는 무엇을 혼동하고 있습니다 만, 여기 당신이 디자인 할 것을 설계 할 때 일반적으로 옵션이 있습니다.

  15. ==============================

    15.질문에 대한 알렉스의 솔루션 및 Guilherme에 대한 감사에서 전 C # 클래스를 생성하기 위해 MySQL을이했다

    질문에 대한 알렉스의 솔루션 및 Guilherme에 대한 감사에서 전 C # 클래스를 생성하기 위해 MySQL을이했다

    set @schema := 'schema_name';
    set @table := 'table_name';
    SET group_concat_max_len = 2048;
    SELECT 
        concat('public class ', @table, '\n{\n', GROUP_CONCAT(a.property_ SEPARATOR '\n'), '\n}') class_
    FROM 
        (select
            CONCAT(
            '\tpublic ',
            case 
                when DATA_TYPE = 'bigint' then 'long'
                when DATA_TYPE = 'BINARY' then 'byte[]'
                when DATA_TYPE = 'bit' then 'bool'
                when DATA_TYPE = 'char' then 'string'
                when DATA_TYPE = 'date' then 'DateTime'
                when DATA_TYPE = 'datetime' then 'DateTime'
                when DATA_TYPE = 'datetime2' then 'DateTime'
                when DATA_TYPE = 'datetimeoffset' then 'DateTimeOffset'
                when DATA_TYPE = 'decimal' then 'decimal'
                when DATA_TYPE = 'double' then 'double'
                when DATA_TYPE = 'float' then 'float'
                when DATA_TYPE = 'image' then 'byte[]'
                when DATA_TYPE = 'int' then 'int'
                when DATA_TYPE = 'money' then 'decimal'
                when DATA_TYPE = 'nchar' then 'char'
                when DATA_TYPE = 'ntext' then 'string'
                when DATA_TYPE = 'numeric' then 'decimal'
                when DATA_TYPE = 'nvarchar' then 'string'
                when DATA_TYPE = 'real' then 'double'
                when DATA_TYPE = 'smalldatetime' then 'DateTime'
                when DATA_TYPE = 'smallint' then 'short'
                when DATA_TYPE = 'smallmoney' then 'decimal'
                when DATA_TYPE = 'text' then 'string'
                when DATA_TYPE = 'time' then 'TimeSpan'
                when DATA_TYPE = 'timestamp' then 'DateTime'
                when DATA_TYPE = 'tinyint' then 'byte'
                when DATA_TYPE = 'uniqueidentifier' then 'Guid'
                when DATA_TYPE = 'varbinary' then 'byte[]'
                when DATA_TYPE = 'varchar' then 'string'
                else '_UNKNOWN_'
            end, ' ', 
            COLUMN_NAME, ' {get; set;}') as property_
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = @table AND table_schema = @schema) a
    ;
    
  16. ==============================

    16.잡아 QueryFirst, SQL 쿼리에서 래퍼 클래스를 생성 비주얼 스튜디오 확장. 당신은하지 ...

    잡아 QueryFirst, SQL 쿼리에서 래퍼 클래스를 생성 비주얼 스튜디오 확장. 당신은하지 ...

    public class MyClass{
        public string MyProp{get;set;}
        public int MyNumberProp{get;set;}
        ...
    }
    

    그리고 보너스로, 그것은에서 던질거야 ...

    public class MyQuery{
        public static IEnumerable<MyClass>Execute(){}
        public static MyClass GetOne(){}
        ...
    }
    

    당신은 당신이 당신의 테이블에 직접 클래스를 기반으로 하시겠습니까? 테이블은 DB에 속한 정적, 정규화 데이터 저장 개념이다. 클래스는 동적 유체 일회용 특정 컨텍스트 아마도 정규화된다. 왜 당신이 작업에 대해 원하는 데이터에 대한 실제 쿼리를 작성하고, QueryFirst 그에서 클래스를 생성 할 수 없습니다.

  17. ==============================

    17.이 포스팅은 나에게 여러 번 저장하고있다. 난 그냥 내 두 센트를 추가 할. 사람들을 위해 그으로 ORMs을 사용하고, 테이블의 20 열 및 해당 CRUD 작업, 그 고통과 시간의 낭비 40 개 다른 테이블과 같이있을 때 대신, 자신의 DAL 클래스를 작성하는 등의니까. I 테이블 엔티티 및 속성에 따라 CRUD 방법을 생성하기 위해 상기 코드를 반복했다.

    이 포스팅은 나에게 여러 번 저장하고있다. 난 그냥 내 두 센트를 추가 할. 사람들을 위해 그으로 ORMs을 사용하고, 테이블의 20 열 및 해당 CRUD 작업, 그 고통과 시간의 낭비 40 개 다른 테이블과 같이있을 때 대신, 자신의 DAL 클래스를 작성하는 등의니까. I 테이블 엔티티 및 속성에 따라 CRUD 방법을 생성하기 위해 상기 코드를 반복했다.

     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 '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
        where object_id = object_id(@TableName)
    ) t
    order by ColumnId
    
    set @Result = @Result  + '
    }'
    
    print @Result
    
    declare @InitDataAccess varchar(max) = 'public class '+ @TableName +'DataAccess 
    { '
    
    declare @ListStatement varchar(max) ='public List<'+@TableName+'> Get'+@TableName+'List()
    {
     String conn = ConfigurationManager.ConnectionStrings["ConnectionNameInWeb.config"].ConnectionString;
     var itemList = new List<'+@TableName+'>();
              try
                {
                    using (var sqlCon = new SqlConnection(conn))
                    {
                        sqlCon.Open();
                        var cmd = new SqlCommand
                        {
                            Connection = sqlCon,
                            CommandType = CommandType.StoredProcedure,
                            CommandText = "StoredProcedureSelectAll"
                        };
                        SqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                          var item = new '+@TableName+'();
    ' 
    select @ListStatement = @ListStatement + '
    item.'+ ColumnName + '= ('+ ColumnType + NullableSign  +')reader["'+ColumnName+'"];
    '
    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 '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
        where object_id = object_id(@TableName)
    ) t
    order by ColumnId
    
    select @ListStatement = @ListStatement +'
                            itemList.Add(item);
                        }
    
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return itemList;
            }'
    
    declare @GetIndividual varchar(max) =  
    'public '+@TableName+' Get'+@TableName+'()
    {
     String conn = ConfigurationManager.ConnectionStrings["ConnectionNameInWeb.config"].ConnectionString;
     var item = new '+@TableName+'();
              try
                {
                    using (var sqlCon = new SqlConnection(conn))
                    {
                        sqlCon.Open();
                        var cmd = new SqlCommand
                        {
                            Connection = sqlCon,
                            CommandType = CommandType.StoredProcedure,
                            CommandText = "StoredProcedureSelectIndividual"
                        };
                         cmd.Parameters.AddWithValue("@ItemCriteria", item.id);
                        SqlDataReader reader = cmd.ExecuteReader();
                        if (reader.Read())
                        {' 
    select @GetIndividual = @GetIndividual + '
    item.'+ ColumnName + '= ('+ ColumnType + NullableSign  +')reader["'+ColumnName+'"];
    '
    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 '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
        where object_id = object_id(@TableName)
    ) t
    order by ColumnId
    
    select @GetIndividual = @GetIndividual +'
    
                        }
    
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return item;
            }'
    
    
    
    declare @InsertStatement varchar(max) = 'public void  Insert'+@TableName+'('+@TableName+' item)
    {
     String conn = ConfigurationManager.ConnectionStrings["ConnectionNameInWeb.config"].ConnectionString;
    
              try
                {
                    using (var sqlCon = new SqlConnection(conn))
                    {
                        sqlCon.Open();
                        var cmd = new SqlCommand
                        {
                            Connection = sqlCon,
                            CommandType = CommandType.StoredProcedure,
                            CommandText = "StoredProcedureInsert"
                        };
    
                        ' 
    select @InsertStatement = @InsertStatement + '
     cmd.Parameters.AddWithValue("@'+ColumnName+'", item.'+ColumnName+');
    '
    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 '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
        where object_id = object_id(@TableName)
    ) t
    order by ColumnId
    
    select @InsertStatement = @InsertStatement +'
    
                        cmd.ExecuteNonQuery();
    
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
    
            }'
    
    declare @UpdateStatement varchar(max) = 'public void  Update'+@TableName+'('+@TableName+' item)
    {
     String conn = ConfigurationManager.ConnectionStrings["ConnectionNameInWeb.config"].ConnectionString;
    
              try
                {
                    using (var sqlCon = new SqlConnection(conn))
                    {
                        sqlCon.Open();
                        var cmd = new SqlCommand
                        {
                            Connection = sqlCon,
                            CommandType = CommandType.StoredProcedure,
                            CommandText = "StoredProcedureUpdate"
                        };
                        cmd.Parameters.AddWithValue("@UpdateCriteria", item.Id);
                        ' 
    select @UpdateStatement = @UpdateStatement + '
     cmd.Parameters.AddWithValue("@'+ColumnName+'", item.'+ColumnName+');
    '
    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 '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
        where object_id = object_id(@TableName)
    ) t
    order by ColumnId
    
    select @UpdateStatement = @UpdateStatement +'
    
                        cmd.ExecuteNonQuery();
    
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
    
            }'
    
    declare @EndDataAccess varchar(max)  = '
    }'
     print @InitDataAccess
     print @GetIndividual
    print @InsertStatement
    print @UpdateStatement
    print @ListStatement
    print @EndDataAccess
    

    물론이 아니 방탄 코드 및 향상시킬 수있다. 그냥이 excelent 솔루션에 기여하고 싶었다

  18. ==============================

    18.약간 상단 응답에서 수정 :

    약간 상단 응답에서 수정 :

    declare @TableName sysname = 'HistoricCommand'
    
    declare @Result varchar(max) = '[System.Data.Linq.Mapping.Table(Name = "' + @TableName + '")]
    public class Dbo' + @TableName + '
    {'
    
    select @Result = @Result + '
        [System.Data.Linq.Mapping.Column(Name = "' + t.ColumnName + '", IsPrimaryKey = ' + pkk.ISPK + ')]
        public ' + ColumnType + NullableSign + ' ' + t.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, 
    (
                    SELECT c.name  AS 'ColumnName', CASE WHEN dd.pk IS NULL THEN 'false' ELSE 'true' END ISPK           
                    FROM        sys.columns c
                        JOIN    sys.tables  t   ON c.object_id = t.object_id    
                        LEFT JOIN (SELECT   K.COLUMN_NAME , C.CONSTRAINT_TYPE as pk  
                            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K 
                                LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                            ON K.TABLE_NAME = C.TABLE_NAME
                                AND K.CONSTRAINT_NAME = C.CONSTRAINT_NAME
                                AND K.CONSTRAINT_CATALOG = C.CONSTRAINT_CATALOG
                                AND K.CONSTRAINT_SCHEMA = C.CONSTRAINT_SCHEMA            
                            WHERE K.TABLE_NAME = @TableName) as dd
                         ON dd.COLUMN_NAME = c.name
                     WHERE       t.name = @TableName            
                ) pkk
    where pkk.ColumnName = t.ColumnName
    order by ColumnId
    
    set @Result = @Result  + '
    }'
    
    print @Result
    

    이는 C #을 선언 전체 LINQ에 필요한 출력한다

    [System.Data.Linq.Mapping.Table(Name = "HistoricCommand")]
    public class DboHistoricCommand
    {
        [System.Data.Linq.Mapping.Column(Name = "HistoricCommandId", IsPrimaryKey = true)]
        public int HistoricCommandId { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "PHCloudSoftwareInstanceId", IsPrimaryKey = true)]
        public int PHCloudSoftwareInstanceId { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "CommandType", IsPrimaryKey = false)]
        public int CommandType { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "InitiatedDateTime", IsPrimaryKey = false)]
        public DateTime InitiatedDateTime { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "CompletedDateTime", IsPrimaryKey = false)]
        public DateTime CompletedDateTime { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "WasSuccessful", IsPrimaryKey = false)]
        public bool WasSuccessful { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "Message", IsPrimaryKey = false)]
        public string Message { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "ResponseData", IsPrimaryKey = false)]
        public string ResponseData { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "Message_orig", IsPrimaryKey = false)]
        public string Message_orig { get; set; }
    
        [System.Data.Linq.Mapping.Column(Name = "Message_XX", IsPrimaryKey = false)]
        public string Message_XX { get; set; }
    
    }
    
  19. ==============================

    19.가장 간단한 방법은 EF, 리버스 엔지니어링이다. http://msdn.microsoft.com/en-US/data/jj593170

    가장 간단한 방법은 EF, 리버스 엔지니어링이다. http://msdn.microsoft.com/en-US/data/jj593170

  20. ==============================

    20.나는 설치에 민간 지역 회원들과 대중 접근 / 뮤 테이터 내 수업을 좋아한다. 나는 알렉스의 스크립트를 수정 한 잘 둘다하는 사람에 관해서는 그렇게하기 위.

    나는 설치에 민간 지역 회원들과 대중 접근 / 뮤 테이터 내 수업을 좋아한다. 나는 알렉스의 스크립트를 수정 한 잘 둘다하는 사람에 관해서는 그렇게하기 위.

    declare @TableName sysname = 'TABLE_NAME'
    declare @result varchar(max) = 'public class ' + @TableName + '
    {'
    
    SET @result = @result + 
    '
        public ' + @TableName + '()
        {}
    ';
    
    select @result = @result + '
        private ' + ColumnType + ' ' + ' m_' + stuff(replace(ColumnName, '_', ''), 1, 1, lower(left(ColumnName, 1))) + ';'
    from
    (
        select 
            replace(col.name, ' ', '_') ColumnName,
            column_id,
            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
        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 column_id
    
    SET @result = @result + '
    '
    
    select @result = @result + '
        public ' + ColumnType + ' ' + ColumnName + ' { get { return m_' + stuff(replace(ColumnName, '_', ''), 1, 1, lower(left(ColumnName, 1))) + ';} set {m_' + stuff(replace(ColumnName, '_', ''), 1, 1, lower(left(ColumnName, 1))) + ' = value;} }' from
    (
        select 
            replace(col.name, ' ', '_') ColumnName,
            column_id,
            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
        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 column_id
    
    set @result = @result  + '
    }'
    
    print @result
    
  21. ==============================

    21.이전 솔루션에 작은 추가 : 기본 스키마에있는 경우 OBJECT_ID (@tablename은)에만 작동합니다.

    이전 솔루션에 작은 추가 : 기본 스키마에있는 경우 OBJECT_ID (@tablename은)에만 작동합니다.

    (Select id from sysobjects where name = @TableName)
    

    스키마의 작품 @tablename 고유 제공.

  22. ==============================

    22.경우에는 내가 그냥 개체 모델에 법인을 구속 할 필요가 나를 떠난 무언가를 원 속성 매핑을 사용하여 코드 첫 번째 접근 방식 작업, 다른 사람에게 유용합니다. 카르노 타우 루스 '대답 덕분에 그래서, 나는 자신의 제안에 따라 그것을 확장 및 개조하면 되겠 어의 몇했다.

    경우에는 내가 그냥 개체 모델에 법인을 구속 할 필요가 나를 떠난 무언가를 원 속성 매핑을 사용하여 코드 첫 번째 접근 방식 작업, 다른 사람에게 유용합니다. 카르노 타우 루스 '대답 덕분에 그래서, 나는 자신의 제안에 따라 그것을 확장 및 개조하면 되겠 어의 몇했다.

    이것은 SQL 스칼라 반환 기능 두 가지 모두의 두 부분을 포함하는 용액에 따라서 의존한다 :

    ALTER function [dbo].[ProperCase] (@cStringToProper varchar(8000))
    returns varchar(8000)
    as
    begin
       declare  @Position int
        select @cStringToProper = stuff(lower(@cStringToProper) , 1 , 1 , upper(left(@cStringToProper , 1)))
            , @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)
    
       while @Position > 0
             select @cStringToProper = stuff(@cStringToProper , @Position , 2 , upper(substring(@cStringToProper , @Position , 2)))
                  , @Position = patindex('%[^a-zA-Z][a-z]%' , @cStringToProper collate Latin1_General_Bin)
    
      select @cStringToProper = replace(@cStringToProper, '_','')
    
       return @cStringToProper
    end
    
    CREATE FUNCTION [dbo].[GetEntityObject] (@NameSpace NVARCHAR(MAX), @TableName NVARCHAR(MAX), @EntityName NVARCHAR(MAX))  RETURNS NVARCHAR(MAX) AS BEGIN
    
    DECLARE @result NVARCHAR(MAX)
    
    SET @result = @result + 'using System;' + CHAR(13) + CHAR(13) 
    
    IF (@NameSpace IS NOT NULL)  BEGIN
        SET @result = @result + 'namespace ' + @NameSpace  + CHAR(13) + '{' + CHAR(13)  END
    
    SET @result = @result + '[Table(name: ' + CHAR(34) + @TableName + CHAR(34) + ')]' + CHAR(13) SET @result = @result + 'public class ' + @EntityName + CHAR(13) + '{' + CHAR(13) 
    
    SET @result = @result + '#region Instance Properties' + CHAR(13)  
    
    SELECT @result = @result + CHAR(13)     + '[Column(name: ' + CHAR(34) + OriginalColumnName + CHAR(34) + ', TypeName = ' + CHAR(34) + DataType
    + CHAR(34) + ')]' + CHAR(13)
        + 'public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13)  FROM (
        SELECT dbo.ProperCase (c.COLUMN_NAME)   AS ColumnName 
            , CASE c.DATA_TYPE   
                WHEN 'bigint' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
                WHEN 'binary' THEN 'Byte[]'
                WHEN 'bit' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END            
                WHEN 'char' THEN 'String'
                WHEN 'date' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
                WHEN 'datetime' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
                WHEN 'datetime2' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                        
                WHEN 'datetimeoffset' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END                                    
                WHEN 'decimal' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                    
                WHEN 'float' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Single?' ELSE 'Single' END                                    
                WHEN 'image' THEN 'Byte[]'
                WHEN 'int' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
                WHEN 'money' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                
                WHEN 'nchar' THEN 'String'
                WHEN 'ntext' THEN 'String'
                WHEN 'numeric' THEN
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                            
                WHEN 'nvarchar' THEN 'String'
                WHEN 'real' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Double?' ELSE 'Double' END                                                                        
                WHEN 'smalldatetime' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
                WHEN 'smallint' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END            
                WHEN 'smallmoney' THEN  
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END                                                                        
                WHEN 'text' THEN 'String'
                WHEN 'time' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END                                         
                WHEN 'timestamp' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END                                    
                WHEN 'tinyint' THEN 
                    CASE C.IS_NULLABLE
                        WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END                                                
                WHEN 'uniqueidentifier' THEN 'Guid'
                WHEN 'varbinary' THEN 'Byte[]'
                WHEN 'varchar' THEN 'String'
                ELSE 'Object'
            END AS ColumnType
            , c.ORDINAL_POSITION        , c.COLUMN_NAME as OriginalColumnName       ,c.DATA_TYPE as DataType
    
    FROM    INFORMATION_SCHEMA.COLUMNS c WHERE   c.TABLE_NAME = @TableName) t ORDER BY t.ORDINAL_POSITION
    
    SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)  
    
    SET @result = @result  + '}' + CHAR(13)
    
    IF (@TableName IS NOT NULL)  BEGIN
        SET @result = @result + CHAR(13) + '}'  END
    
    return @result END
    

    MS SQL 관리 Studio 내에서 사용 :

    당신은 비주얼 스튜디오에 복사하여 붙여 넣을 수있는 열 값에 발생합니다.

    그것은 사람을 도움이 있다면, 좋은!

  23. ==============================

    23.나는 klassify, 한 번에 지정된 데이터베이스의 모든 클래스를 생성하는 콘솔 응용 프로그램으로 여기에 여러 SQL 기반의 답변, 알렉스 아자 주로 루트 대답에서 아이디어를 포장 :

    나는 klassify, 한 번에 지정된 데이터베이스의 모든 클래스를 생성하는 콘솔 응용 프로그램으로 여기에 여러 SQL 기반의 답변, 알렉스 아자 주로 루트 대답에서 아이디어를 포장 :

    예를 들어, 다음과 같은 테이블 사용자 지정 :

    +----+------------------+-----------+---------------------+
    | Id |       Name       | Username  |        Email        |
    +----+------------------+-----------+---------------------+
    |  1 | Leanne Graham    | Bret      | Sincere@april.biz   |
    |  2 | Ervin Howell     | Antonette | Shanna@melissa.tv   |
    |  3 | Clementine Bauch | Samantha  | Nathan@yesenia.net  |
    +----+------------------+-----------+---------------------+
    

    klassify 이런 모습 Users.cs라고하는 파일을 생성합니다 :

        public class User 
        {
            public int Id {get; set; }
            public string Name { get;set; }
            public string Username { get; set; }
            public string Email { get; set; }
        }
    

    그것은 모든 테이블에 대한 출력 한 파일을 것이다. 사용하지 않는 무엇을 버리십시오.

    용법

     --out, -o:
            output directory     << defaults to the current directory >>
     --user, -u:
            sql server user id   << required >>
     --password, -p:
            sql server password  << required >>
     --server, -s:
            sql server           << defaults to localhost >>
     --database, -d:
            sql database         << required >>
     --timeout, -t:
            connection timeout   << defaults to 30 >>
     --help, -h:
            show help
    
  24. ==============================

    24.그냥 내가 관심있는 사람을위한 최고 응답 내 자신의 변화를 추가 할 거라고 생각했다. 주요 기능은 다음과 같습니다

    그냥 내가 관심있는 사람을위한 최고 응답 내 자신의 변화를 추가 할 거라고 생각했다. 주요 기능은 다음과 같습니다

  25. ==============================

    25.당신은 한 테이블은 두 개의 열을 포함하고 'tblPeople'같은 것을 호출로했다.

    당신은 한 테이블은 두 개의 열을 포함하고 'tblPeople'같은 것을 호출로했다.

    당신은 항상 당신의 자신의 SQL 래퍼를 작성할 수 있습니다. 사실 나는 어떤 방식으로, 생성 된 코드를 싫어, 그런 식으로 할 것을 선호합니다.

    어쩌면 DAL 클래스를 생성하고이 그 사람에 대한 데이터베이스를 쿼리이 getPerson (INT 아이디)라는 방법을 다음 결과 세트로부터 Person 객체를 생성합니다.

  26. from https://stackoverflow.com/questions/5873170/generate-class-from-database-table by cc-by-sa and MIT license