tags:

views:

211

answers:

2

I'm curious if there is support in the .NET Framework to map .NET data types to the corresponding enumeration SqlDbType that represents the data type in SQL.

For Instance:

dim mySqlDbType as SqlDbType = SomeFunction(GetType(myObject))
+3  A: 

You're looking for SqlMetadata.InferFromValue.

280Z28
+1 This is a great find.
Achilles
A: 

Any open source code generation tool or O/RM should have a dictionary or function to map from SqlDbType to .NET type and back. For example, from Data Tier Generator:

 internal static string GetCsType(Column column)
 {
  switch (column.Type.ToLower())
  {
   case "binary":
    return "byte[]";
   case "bigint":
    return "long";
   case "bit":
    return "bool";
   case "char":
    return "string";
   case "datetime":
    return "DateTime";
   case "decimal":
    return "decimal";
   case "float":
    return "float";
   case "image":
    return "byte[]";
   case "int":
    return "int";
   case "money":
    return "decimal";
   case "nchar":
    return "string";
   case "ntext":
    return "string";
   case "nvarchar":
    return "string";
   case "numeric":
    return "decimal";
   case "real":
    return "decimal";
   case "smalldatetime":
    return "DateTime";
   case "smallint":
    return "short";
   case "smallmoney":
    return "float";
   case "sql_variant":
    return "byte[]";
   case "sysname":
    return "string";
   case "text":
    return "string";
   case "timestamp":
    return "DateTime";
   case "tinyint":
    return "byte";
   case "varbinary":
    return "byte[]";
   case "varchar":
    return "string";
   case "uniqueidentifier":
    return "Guid";
   default:  // Unknow data type
    throw (new Exception("Invalid SQL Server data type specified: " + column.Type));
  }
 }
Axl
I don't like this approach because it doesn't scale. What happens when Microsoft adds another value to SqlDbType?
Achilles