Question

How do I best convert a System.Data.DbType enumeration value to the corresponding (or at least one of the possible corresponding) System.Type values?

For example:

DbType.StringFixedLength -> System.String 
DbType.String -> System.String
DbType.Int32 -> System.Int32

I've only seen very "dirty" solutions but nothing really clean.

(yes, it's a follow up to a different question of mine, but it made more sense as two seperate questions)

Was it helpful?

Solution

AFAIK there is no built-in converter in .NET for converting a SqlDbType to a System.Type. But knowing the mapping you can easily roll your own converter ranging from a simple dictionary to more advanced (XML based for extensability) solutions.

The mapping can be found here: http://www.carlprothman.net/Default.aspx?tabid=97

OTHER TIPS

System.Data.SqlClient objects use the MetaType component to translate DbType and SqlDbType to .NET CLR Types. Using reflection, you could leverage this ability if needed:

var dbType = DbType.Currency;

Type metaClrType = Type.GetType(
    "System.Data.SqlClient.MetaType, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
    true,
    true
    );

object metaType = metaClrType.InvokeMember(
    "GetMetaTypeFromDbType",
    BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic,
    null,
    null,
    new object[] { dbType }
);

var classType = (Type)metaClrType.InvokeMember(
    "ClassType",
    BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
    null,
    metaType,
    null
);

string cSharpDataType = classType.FullName;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top