4

Tengo una base de datos creada en MS SQL Server con diferentes tablas en ella. Lo que estoy intentando hacer es generar a partir de este modelo "importarlo" de alguna forma al Visual Studio 2013 (Visual Basic - Framework 4.0) y se generen clases de forma automática.

Por ejemplo tengo la tabla Usuario con los campos:

  • ID Bigint
  • Nombre Varchar(255)
  • Apellido varchar(255)

Lo que debería generarme en mi proyecto de VB sería una clase: Usuario.vb (class) con los atributos:

  • dim ID as long
  • dim Nombre as String
  • dim Apellido as String

Esto fue un comentario que es escuche que era posible hacer. Pero no pude encontrar la forma, en algunos lados leí que quizás era posible usar Entity Framework pero no lo logré.

¿Cómo lo podría lograr?

5
  • Hola, bienvenido a SOes, pregunta ¿por qué crearlas en VB 4? Sabiendo que es a modo de práctica y siendo que existen lenguajes más robustos y relativamente más sencillos de usar.
    – Phi
    el 10 feb. 2017 a las 20:08
  • Soy desarrollador web y el entorno que uso es visual studio 2013 y codifico en vb para el framework 4.0, quizas me exprese mal. Ayer escuche que podia generar las clases automaticamente y estuve investigando pero no logre encontrar lo que necesitaba. Por eso realizo la consulta el 10 feb. 2017 a las 20:13
  • Ah bien, ahora lo entiendo, sería bueno que editaras la pregunta para que no se mal entienda, ya que así como está puedes recibir una respuesta que no es la que esperas :)
    – Phi
    el 10 feb. 2017 a las 20:14
  • De igual forma, te recomiendo poner segmentos de código de lo que has intentado, con esto, nos daremos una idea más exacta del resultado que esperas obtener.
    – Phi
    el 10 feb. 2017 a las 20:19
  • Gracias, ahi modifique la pregunta. el 10 feb. 2017 a las 20:32

1 respuesta 1

4

Ejecuta el siguiente script en SQL Server Management Studio para obtener la clase a partir del resultado.

----------------------------------
-- DW: 11/04/2011
-- This script will build a class file with 
-- private fields and public properties from
-- the table specified in the @TableName variable.
----------------------------------

DECLARE @TableName varchar(50)
SET @TableName = 'Usuario'

SET NOCOUNT ON; -- Hide row count so printed output is not affected

DECLARE @DataTypeName varchar(50)
DECLARE @NewLine char
DECLARE @ColumnName varchar(50)
DECLARE @DataType varchar(50)
DECLARE @FieldName varchar(50)

--SET @NewLine = char(13)

-- Start Output
--PRINT '' + @NewLine;
PRINT 'Public Class ' + @TableName;
PRINT '';
PRINT '#Region "Declarations"';
PRINT '';

-- Declarations
DECLARE DeclarationCursor CURSOR SCROLL FOR 
    SELECT
        columns.name [ColumnName],
        CASE 
            WHEN columns.system_type_id = 34    THEN 'Byte[]'
            WHEN columns.system_type_id = 35    THEN 'String'
            WHEN columns.system_type_id = 36    THEN 'System.Guid'
            WHEN columns.system_type_id = 48    THEN 'Byte'
            WHEN columns.system_type_id = 52    THEN 'Short'
            WHEN columns.system_type_id = 56    THEN 'Integer'
            WHEN columns.system_type_id = 58    THEN 'System.DateTime'
            WHEN columns.system_type_id = 59    THEN 'float'
            WHEN columns.system_type_id = 60    THEN 'Decimal'
            WHEN columns.system_type_id = 61    THEN 'System.DateTime'
            WHEN columns.system_type_id = 62    THEN 'double'
            WHEN columns.system_type_id = 98    THEN 'Object'
            WHEN columns.system_type_id = 99    THEN 'String'
            WHEN columns.system_type_id = 104   THEN 'Boolean'
            WHEN columns.system_type_id = 106   THEN 'Decimal'
            WHEN columns.system_type_id = 108   THEN 'Decimal'
            WHEN columns.system_type_id = 122   THEN 'Decimal'
            WHEN columns.system_type_id = 127   THEN 'long'
            WHEN columns.system_type_id = 165   THEN 'Byte[]'
            WHEN columns.system_type_id = 167   THEN 'String'
            WHEN columns.system_type_id = 173   THEN 'Byte[]'
            WHEN columns.system_type_id = 175   THEN 'string'
            WHEN columns.system_type_id = 189   THEN 'Long'
            WHEN columns.system_type_id = 231   THEN 'String'
            WHEN columns.system_type_id = 239   THEN 'String'
            WHEN columns.system_type_id = 241   THEN 'String'
            WHEN columns.system_type_id = 241   THEN 'String'
        END [DataType]
FROM              sys.tables tables
    INNER JOIN    sys.schemas schemas ON (tables.schema_id = schemas.schema_id )
    INNER JOIN    sys.columns columns ON (columns.object_id = tables.object_id) 
WHERE
    tables.name = @TableName
ORDER BY 
    columns.object_id ASC;


OPEN DeclarationCursor;

FETCH NEXT FROM DeclarationCursor 
INTO @ColumnName, @DataType;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @FieldName = '_' + LOWER(SUBSTRING(@ColumnName, 1,1)) + SUBSTRING(@ColumnName, 2, LEN(@ColumnName)-1)
    PRINT '    Private ' + @FieldName + ' As ' + @DataType;

    FETCH NEXT FROM DeclarationCursor 
    INTO @ColumnName, @DataType;
END
PRINT ''; 
PRINT '#End Region';
PRINT ''; 
PRINT '#Region "Properties"';
PRINT '';

FETCH FIRST FROM DeclarationCursor 
INTO @ColumnName, @DataType;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @FieldName = '_' + LOWER(SUBSTRING(@ColumnName, 1,1)) + SUBSTRING(@ColumnName, 2, LEN(@ColumnName)-1)

    PRINT '    Public Property ' + @ColumnName + ' As ' + @DataType;
    PRINT '        Get';
    PRINT '            Return ' + @FieldName;
    PRINT '        End Get';
    PRINT '        Set';
    PRINT '            ' + @FieldName + ' = value';
    PRINT '        End Set';
    PRINT '    End Property';
    PRINT ''; 

    FETCH NEXT FROM DeclarationCursor 
    INTO @ColumnName, @DataType;
END

PRINT ''; 
PRINT '#End Region';
PRINT ''; 


DECLARE @FIELDS varchar(max)
SET @FIELDS = ''

FETCH FIRST FROM DeclarationCursor 
INTO @ColumnName, @DataType;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @FieldName = LOWER(SUBSTRING(@ColumnName, 1,1)) + SUBSTRING(@ColumnName, 2, LEN(@ColumnName)-1)
    SET @FIELDS = @FIELDS + 'byval ' + @FieldName + ' as ' + @DataType + ', '

    FETCH NEXT FROM DeclarationCursor 
    INTO @ColumnName, @DataType;
END

SET @FIELDS = SUBSTRING(@FIELDS, 1, (LEN(@FIELDS) - 1))

PRINT '#Region "Constructors"';
PRINT '';
PRINT '    Public Sub New()';
PRINT '        ';
PRINT '    End Sub';
PRINT '';
PRINT '    Public Sub New(' + @FIELDS + ')'
PRINT '        Me.New()';
PRINT '    End Sub';
PRINT '';
PRINT '#End Region';
PRINT ''; 

CLOSE DeclarationCursor;
DEALLOCATE DeclarationCursor;

-- End of Class
PRINT 'End Class';

En caso quieras generar para otra tabla, solo tienes que actualizar el valor de @TableName.

introducir la descripción de la imagen aquí

Referencia

2
  • Gracias es lo que necesitaba! el 13 feb. 2017 a las 13:54
  • Definitivamente muy practico, muchas gracias!!! el 19 oct. 2017 a las 21:45

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.