0

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.

8
  • 2
    you can make your own mapping and then make some method whic accepts one type and returns equivalent in sql Commented Oct 22, 2013 at 12:14
  • 1
    @wudzik thats what i am thinking but it means that i have to check for every type, was wondering if there was somthing built in for this that could help Commented Oct 22, 2013 at 12:17
  • 3
    C# doesn't have a special feature for this. We use to have a mapping table, wudzik mentioned that. In fact, it's not possible to be very accurate sometimes because it depends on your requirements. In our case we had Decimal c# types mapped to different precisions in the database. Commented Oct 22, 2013 at 12:20
  • 1
    You could create a dictionary for all the c# types and use it as mentioned in the SO link - stackoverflow.com/questions/10997526/… Commented Oct 22, 2013 at 12:21
  • 3
    You could use an ORM, such as NHibernate, that would do it all for you. Commented Oct 22, 2013 at 12:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.