Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I best convert a DbType to System.Type?

Tags:

.net

converter

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)

like image 868
Alex Duggleby Avatar asked Sep 18 '08 09:09

Alex Duggleby


2 Answers

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

like image 180
Jorge Ferreira Avatar answered Oct 13 '22 00:10

Jorge Ferreira


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;
like image 23
Jon Banta Avatar answered Oct 12 '22 23:10

Jon Banta