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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With