How to resolve System.Type to System.Data.DbType?

前端 未结 5 616
礼貌的吻别
礼貌的吻别 2020-12-04 22:20

What is the best way to find System.Data.DbType enumeration value for Base Class Library types in System namespace?

5条回答
  •  长情又很酷
    2020-12-04 22:37

    A common way is to have a type map, with all supported types (different connectors/providers supports different types) explicitly mapped. Here is the type map for Dapper:

    typeMap = new Dictionary();
    typeMap[typeof(byte)] = DbType.Byte;
    typeMap[typeof(sbyte)] = DbType.SByte;
    typeMap[typeof(short)] = DbType.Int16;
    typeMap[typeof(ushort)] = DbType.UInt16;
    typeMap[typeof(int)] = DbType.Int32;
    typeMap[typeof(uint)] = DbType.UInt32;
    typeMap[typeof(long)] = DbType.Int64;
    typeMap[typeof(ulong)] = DbType.UInt64;
    typeMap[typeof(float)] = DbType.Single;
    typeMap[typeof(double)] = DbType.Double;
    typeMap[typeof(decimal)] = DbType.Decimal;
    typeMap[typeof(bool)] = DbType.Boolean;
    typeMap[typeof(string)] = DbType.String;
    typeMap[typeof(char)] = DbType.StringFixedLength;
    typeMap[typeof(Guid)] = DbType.Guid;
    typeMap[typeof(DateTime)] = DbType.DateTime;
    typeMap[typeof(DateTimeOffset)] = DbType.DateTimeOffset;
    typeMap[typeof(byte[])] = DbType.Binary;
    typeMap[typeof(byte?)] = DbType.Byte;
    typeMap[typeof(sbyte?)] = DbType.SByte;
    typeMap[typeof(short?)] = DbType.Int16;
    typeMap[typeof(ushort?)] = DbType.UInt16;
    typeMap[typeof(int?)] = DbType.Int32;
    typeMap[typeof(uint?)] = DbType.UInt32;
    typeMap[typeof(long?)] = DbType.Int64;
    typeMap[typeof(ulong?)] = DbType.UInt64;
    typeMap[typeof(float?)] = DbType.Single;
    typeMap[typeof(double?)] = DbType.Double;
    typeMap[typeof(decimal?)] = DbType.Decimal;
    typeMap[typeof(bool?)] = DbType.Boolean;
    typeMap[typeof(char?)] = DbType.StringFixedLength;
    typeMap[typeof(Guid?)] = DbType.Guid;
    typeMap[typeof(DateTime?)] = DbType.DateTime;
    typeMap[typeof(DateTimeOffset?)] = DbType.DateTimeOffset;
    typeMap[typeof(System.Data.Linq.Binary)] = DbType.Binary;
    

    To get a relevant DbType, all you need to do is:

    var type = typeMap[typeof(string)]; // returns DbType.String
    

提交回复
热议问题