[Dicas] Como converter uma tabela em uma classe C#?
Como ganhar tempo ao criar classe baseada em uma tabela do banco de dados?
No post passado falei sobre ferramentas que agilizam o dia a dia do desenvolvedor, além das ferramentas, podemos ter alguns códigos prontos que podem agilizar o nosso processo de desenvolvimento.
Hoje trarei uma dica de um código SQL que utilizo de vez em quando, onde eu passo uma determinada tabela do banco de dados do Sql Server e ele me retorna uma classe C#.
Antigamente era muito comum criarmos o banco de dados primeiro e logo em seguida criamos nossas classes do .net, então este script foi muito útil pra mim naquela época. Atualmente não utilizo tanto pelo fato de trabalhar com ORM Entity Framework utilizando Code First e Migrations, então este script perdeu um pouco o sentido pra mim.
Lembrando que o script cria a classe C# baseada em uma tabela do banco de dados, ou seja, você pode ter vários cenários que o script pode ser útil.
Gostaria de ressaltar também que existem extensões para o Visual Studio que nos permitem ter um resultado semelhante.
Create csharp model from table
Confira o script sql abaixo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
declare @TableName sysname = 'Usuario' 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 |
Confira o resultado:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Usuario { public string UsuarioID { get; set; } public string Nome { get; set; } public string Email { get; set; } public string Senha { get; set; } public DateTime DataCadastro { get; set; } public DateTime DataModificacao { get; set; } public DateTime? DataUltimoAcesso { get; set; } public bool Ativo { get; set; } public bool Excluido { get; set; } } |
Para maiores informações acesse meu diretório do GitHub através do link abaixo:
Clique aqui para acessar o script no GitHub
Participe do nosso Slack clicando no link abaixo e tire suas dúvidas:
https://ilovecodeteam.herokuapp.com/
Não esqueça de curtir nossa fanpage, nosso canal no youtube e participar do nosso grupo do Facebook.
About author
You might also like
Hangout – Conhecendo o angularJS 2 com André Baltieri e Nicolas Takashi
Share this on WhatsAppConfira Hangout ao vivo sobre Angular 2 e tire suas dúvidas Sabemos que o Angular JS é um framework javascript mantido pela gigante Google e que cresce
Veja como criar seu próprio servidor Nuget!
Share this on WhatsAppE ai pessoal, beleza? Bom espero que esteja tudo bem com vocês. Já faz um bom tempo que não tenho oportunidade para gravar novos vídeos técnicos. Bom, como
Veja como usar a classe Faker no C#
Share this on WhatsAppE ai pessoal, tudo certo com vocês? Bom espero que sim! Devido hoje ser feriado de sexta-feira santa, resolvi aproveitar o tempo livre para falar de uma classe
5 Comments
Joaquim
agosto 24, 02:02paulorogerio
agosto 24, 11:09Clowbr15
agosto 26, 12:40paulorogerio
agosto 26, 14:10Carlos
abril 26, 10:57