Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 48233
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T16:14:52+00:00 2026-05-10T16:14:52+00:00

Does anyone know a way to auto-generate database tables for a given class? I’m

  • 0

Does anyone know a way to auto-generate database tables for a given class? I’m not looking for an entire persistence layer – I already have a data access solution I’m using, but I suddenly have to store a lot of information from a large number of classes and I really don’t want to have to create all these tables by hand. For example, given the following class:

class Foo {     private string property1;     public string Property1     {         get { return property1; }         set { property1 = value; }     }      private int property2;     public int Property2     {         get { return property2; }         set { property2 = value; }     } } 

I’d expect the following SQL:

CREATE TABLE Foo (     Property1 VARCHAR(500),     Property2 INT ) 

I’m also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be :

class Foo {     private string property1;     public string Property1     {         get { return property1; }         set { property1 = value; }     }      private System.Management.ManagementObject property2;     public System.Management.ManagementObject Property2     {         get { return property2; }         set { property2 = value; }     } } 

How could I handle this?

I’ve looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class’ properties, but it’s clunky and the complex data types have me stumped.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T16:14:53+00:00Added an answer on May 10, 2026 at 4:14 pm

    It’s really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point:

    using System; using System.Collections.Generic; using System.Text; using System.Reflection;  namespace TableGenerator {     class Program     {         static void Main(string[] args)         {             List<TableClass> tables = new List<TableClass>();              // Pass assembly name via argument             Assembly a = Assembly.LoadFile(args[0]);              Type[] types = a.GetTypes();              // Get Types in the assembly.             foreach (Type t in types)             {                 TableClass tc = new TableClass(t);                                 tables.Add(tc);             }              // Create SQL for each table             foreach (TableClass table in tables)             {                 Console.WriteLine(table.CreateTableScript());                 Console.WriteLine();             }              // Total Hacked way to find FK relationships! Too lazy to fix right now             foreach (TableClass table in tables)             {                 foreach (KeyValuePair<String, Type> field in table.Fields)                 {                     foreach (TableClass t2 in tables)                     {                         if (field.Value.Name == t2.ClassName)                         {                             // We have a FK Relationship!                             Console.WriteLine('GO');                             Console.WriteLine('ALTER TABLE ' + table.ClassName + ' WITH NOCHECK');                             Console.WriteLine('ADD CONSTRAINT FK_' + field.Key + ' FOREIGN KEY (' + field.Key + ') REFERENCES ' + t2.ClassName + '(ID)');                             Console.WriteLine('GO');                          }                     }                 }             }         }     }      public class TableClass     {         private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();         private string _className = String.Empty;          private Dictionary<Type, String> dataMapper         {             get             {                 // Add the rest of your CLR Types to SQL Types mapping here                 Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();                 dataMapper.Add(typeof(int), 'BIGINT');                 dataMapper.Add(typeof(string), 'NVARCHAR(500)');                 dataMapper.Add(typeof(bool), 'BIT');                 dataMapper.Add(typeof(DateTime), 'DATETIME');                 dataMapper.Add(typeof(float), 'FLOAT');                 dataMapper.Add(typeof(decimal), 'DECIMAL(18,0)');                 dataMapper.Add(typeof(Guid), 'UNIQUEIDENTIFIER');                  return dataMapper;             }         }          public List<KeyValuePair<String, Type>> Fields         {             get { return this._fieldInfo; }             set { this._fieldInfo = value; }         }          public string ClassName         {             get { return this._className; }             set { this._className = value; }         }          public TableClass(Type t)         {             this._className = t.Name;              foreach (PropertyInfo p in t.GetProperties())             {                 KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);                  this.Fields.Add(field);             }         }          public string CreateTableScript()         {             System.Text.StringBuilder script = new StringBuilder();              script.AppendLine('CREATE TABLE ' + this.ClassName);             script.AppendLine('(');             script.AppendLine('\t ID BIGINT,');             for (int i = 0; i < this.Fields.Count; i++)             {                 KeyValuePair<String, Type> field = this.Fields[i];                  if (dataMapper.ContainsKey(field.Value))                 {                     script.Append('\t ' + field.Key + ' ' + dataMapper[field.Value]);                 }                 else                 {                     // Complex Type?                      script.Append('\t ' + field.Key + ' BIGINT');                 }                  if (i != this.Fields.Count - 1)                 {                     script.Append(',');                 }                  script.Append(Environment.NewLine);             }              script.AppendLine(')');              return script.ToString();         }     } } 

    I put these classes in an assembly to test it:

    public class FakeDataClass {     public int AnInt     {         get;         set;     }      public string AString     {         get;         set;     }      public float AFloat     {         get;         set;     }      public FKClass AFKReference     {         get;         set;     } }  public class FKClass     {         public int AFKInt         {             get;             set;         }     } 

    And it generated the following SQL:

    CREATE TABLE FakeDataClass (          ID BIGINT,          AnInt BIGINT,          AString NVARCHAR(255),          AFloat FLOAT,          AFKReference BIGINT )   CREATE TABLE FKClass (          ID BIGINT,          AFKInt BIGINT )   GO ALTER TABLE FakeDataClass WITH NOCHECK ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID) GO 

    Some further thoughts…I’d consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc…Just to get you started.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 118k
  • Answers 118k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Are you just using TMail, or are you using it… May 11, 2026 at 11:29 pm
  • Editorial Team
    Editorial Team added an answer In [1]: def grp(pat, txt): ...: r = re.search(pat, txt)… May 11, 2026 at 11:29 pm
  • Editorial Team
    Editorial Team added an answer If you want to prevent tampering, you want signing/hashing, not… May 11, 2026 at 11:29 pm

Related Questions

Does anyone know a way to auto-generate database tables for a given class? I'm
I'm using the table class that auto-generates a table for me from an array
My question is similar to this one but for a Rails app. I have
Does anyone know of any way to suppress the Vista fade animations on scroll
I am still learning the whole WCF thing, so please bear with me here.

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.