Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate class from datatable or database table

I have a project where a client can import an excel file, csv, or tab-delimited file. This file is loaded into a datatable which I convert into a SQLite database table. I'd really prefer to work with strongly typed objects vs datatables so is there a way to easily convert the database table created into a strongly typed class using reflection? The kicker is the file imported into the application will always be different, (ie. different columns) so I can't really hardcode any strongly typed objects, they are always going to have to be generated on the fly.

like image 454
user337816 Avatar asked Jul 20 '10 13:07

user337816


People also ask

How do you create a class in SQL?

Open up SSMS (SQL-Server Management Studio), select the database in object explorer and create a new query. In the parameter @TableName place the table name there. Make sure you have selected the database properly or use a USE statement. Now run the statement and this produces a class for the table.


1 Answers

In theory, you could create an assembly using something like Reflection.Emit, or even by generating code files and calling the compiler to build these into an assembly.

However, I'm not sure how this would be useful. Provided that the schema of these tables is determined at run-time, any usage of these generated classes wouldn't be able to use these strongly-typed properties you've added without using reflection, and at that point you're essentially dealing with something weakly typed with the added performance hit of reflection. Dynamic types in C# 4.0 might eliminate the performance hit, but you're still adding a lot of complexity for no real benefit.

like image 104
Ryan Brunner Avatar answered Sep 28 '22 05:09

Ryan Brunner