简体   繁体   中英

Not sure why in c# I get a totally different TypeCode from a DbType within a SQL command parameter object?

I am sure someone is going to shoot this one down in flames.. although the concept from what I can see looks ok...

Basically I am trying to dynamically set a SQL command paramter type and value. So basically I am:

  1. Getting the DbType of the parameter dynamically.. so that part is fine - just referencing like: DbType ParamDBtype = cmd.Parameters[Param1Variable.DbType;
  2. Then (stupidly or not!) I am trying to get the Type for within .NET so I can convert value to the correct type (because in my case I am just getting value/pairs as strings.. hence the reason for getting the DbType to know what type to convert to)

So apparently I can do: TypeCode ParamDBtypeCode = cmd.Parameters[Param1Variable.DbType.GetTypeCode();

Now the TypeCode can be used when using the Convert statement:

Convert.ChangeType(Param1Value, ParamDBtypeCode)

Well it works.. sort of, because I had a param that was an integer, and the conversion converted that value to an int.. but then I had a param which was an AnsiString DbType, and the TypeCode of that param came back as int16 still???

Anyone had this type of issue, or can point me in a better direction?

Essentially I am trying to assign/convert values to the stored procedure dynamically..

Thanks for any help..

What you are seeing there is object.GetTypeCode() on the value - and in the case of a DbType the "value" is the enum . And the type-code of an enum is simply the enum's underlying type: int in this case. It will report int for every DbType - even those that don't exist:

var dbtype = (DbType)(-12341);
var typeCode = dbtype.GetTypeCode(); // Int32

What you are trying to do has nothing to do with the DbType 's GetTypeCode() . The problem here is the " apparently ".

If you really want to map an enum to something else, a switch is ideal. It is entirely possible that you will need to provide the mapping yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM