Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate C# Class Code for Table in Visual Studio

I have multiple tables in my Server Explore database file. I want to generate auto code of Classes for tables, so all classes with their attributes, constructor and getter setter methods automatically generate.

Kindly tell me steps to do so.

like image 492
m3nhaq Avatar asked Dec 22 '22 07:12

m3nhaq


2 Answers

Not autogenerate, but it's not hard to use sql and information_schema to output a class definition, with the class named after the table and the columns being mappped to properties. From there you can have it generate create, updates and deletes (I like to use merge for crate/updates under SQL Server 2008).

Do them one at a time and it's mainly string concatination. The below should get you started....

declare @class varchar(max);

; with typemapping as (
 Select 'varchar' as DATA_TYPE, 'string' ctype
 union
 Select 'int', 'int'
)
select @class = isnull(@class + char(10), '') + 'public ' +
       tm.ctype +' ' + column_name +
       ' { get; set; }'
from information_schema.columns sc
   inner join typemapping tm on sc.data_type = tm.data_type
where table _name ='yourtbl'

print @class;

The rest is left as an exercise for the reader as they say mainly because the details are up to you, instead of auto properties you could use backing variables, put standard logic in the properties, make the value types nullable, when making your own code generator, make it fit your patterns/styles/needs.

like image 184
jmoreno Avatar answered Jan 07 '23 16:01

jmoreno


If you use Entity Framework check the steps this article:

Generating EF Code First model classes from an existing database

like image 38
Acaz Souza Avatar answered Jan 07 '23 16:01

Acaz Souza