Skip to content
Advertisement

Create SQL Server table from user-defined class [closed]

I am creating a mini-ORM to learn reflection better in C#.

Also I want to use Native & Pure C# and do not use Entity Framework or SQL Server Management Objects.

public static void CreateTable(Type tableType, string connectionString)
{
     // codes to create table in database
}

The problem is the CreateTable method, there are lots of problems in it, for example :

  • I could not find any standard way to create a table from user-defined class. How can I generate database tables from C# classes?: this solution is good but not ideal. Maybe it crashes in some situations.

  • DataTypes!
    There is no integration between C# and SQL Server datatypes. For example varchar, nvarchar and text all are (or map to) string !

So when a user creates this class :

public class Person
{        
   public int ID { get; set; }        
   public string Name { get; set; }
}

which SQL Server datatype should I use for Name?

Finally if generating a SQL query and executing it is best way for this question, what is your suggestion?

Advertisement

Answer

Which SQL-type should I use for Name ???

If you’re looking at Entity Framework as an example to follow, by default they map System.String to NVARCHAR(MAX) in all cases. Using property attributes in the Code First entity model (e.g. [Column(DbType = "CHAR(10)")] allows the developer to explicity specify column types.

Maybe you could follow this approach and default to the all encompassing NVARCHAR(MAX) for all strings and create some simple attributes within your ORM for special cases. You wont know string lengths until runtime, after all.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement