I am trying to create an sql table from a T, however I am having problems with getting the right c# type to the right sql type.
Here is my method,
public static void CreateSqlTableFromT<T>(string connectionString) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
StringBuilder query = new StringBuilder();
query.Append("CREATE TABLE ");
query.Append(typeof(T).Name);
query.Append(" ( ");
for (int i = 0; i < properties.Count; i++)
{
query.Append(properties[i]);
query.Append(" ");
query.Append(properties[i].GetType());
query.Append(", ");
}
if (properties.Count > 1) { query.Length -= 2; }
query.Append(")");
using (var con=new SqlConnection(connectionString))
{
con.Open();
SqlCommand createTableCommand = new SqlCommand(query.ToString(), con);
createTableCommand.ExecuteNonQuery();
}
}
In this line, I want to convert the C# variable type to an equivalent SQL type
query.Append(properties[i].GetType());
Is there a way in c# to get the matching sql type from a c# type without having to do a lot of if statements?
For example, a c# decimal should be converted to money.