Generate SQL create table statement from C# classes

David Gray 176 Reputation points
2024-01-31T09:58:52.75+00:00

Hi, I have a load of SQL server tables to create (lots of columns) and I'm wondering if there's a way to generate a script from my C# classes? I have googled and also asked ChatGPT but keep getting suggestions about using Entity Framework to create the tables. I don't want to do this as my application is using Dapper already, and being honest I just want to generate the scripts.
Is this possible? Many thanks

SQL Server | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2024-01-31T11:37:33.09+00:00

    Why not create a console project, reverse engineer the database tables using EF Power Tools to generate classes than take those classes and copy them to your project that is setup with Dapper. When reverse engineering the database with EF Power Tools there is an option to set the namespace which defaults to the current project, change it to the Dapper project namespace so when copying to the Dapper project you are set. May need some tweaks once copied. EF Power Tools is easy to use and allows regeneration of models if tables or columns are added, deleted and/or modified. Scripting: I have a script to generate classes for table but does not create for SQL with JOINS.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 78,236 Reputation points Volunteer Moderator
    2024-01-31T16:54:24.17+00:00

    if you created POCO objects for your dapper queries, then write a quick program or unit test, that generates the sql table definition from the POCO object via reflection. you won't have the size for strings, so just use a default like varchar(50). you can create a dictionary of table name to POCO object and just loop thru the dictionary.

    learning to write code generators is a good skill.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.