Converting from DbType to [Sql]DbType is easy

by Miha Markič 14. September 2006 12:57

I often see question on how to convert from DbType to SqlDbType (or any other *DbType). This is often required if you do some database independent code with ado.net. One way is certainly a gigantic switch block, such as:

private SqlDbType FromDbType(DbType type) { switch (type) { case System.Data.DbType.AnsiStringFixedLength: case System.Data.DbType.StringFixedLength: return SqlDbType.Char; ; case System.Data.DbType.AnsiString: case System.Data.DbType.String: return SqlDbType.VarChar; case System.Data.DbType.Binary: return SqlDbType.Binary; ........ }

However, this is not the best solution as elegant conversion method is already present within .net. Here it is:

DbType type = DbType.Int32; SqlParameter parm = new SqlParameter(); try { parm.DbType = type; } catch (Exception ex) { // can't map } SqlDbType sqlDbType = parm.SqlDbType;

The trick is to use database specific parameter, in this case Sql Server's SqlParameter. And don't forget to wrap DbType assignment in try/catch block as an ArgumentException will be thrown when mapping doesn't exist between given DbType and target database specific type.

The implementation could be nicer (perhaps through a static method) but hey, it works just fine.

Tags:

.net

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Miha Markic

About me
Righthand
 
Microsoft MVP
 
Developer Express' DXSquad
INETA Country Leader for Slovenia
INETA Country Leader for Slovenia

Slovene Developer Users Group Lead
Friends of Red-Gate
LLBLGenPro Partner

Miha currently works as a free lance consultant and software developer specialized in .net area.
He graduated in Computer and information science at the University of Ljubljana, Slovenia. He has accumulated experience in various programming languages such as Java, Visual Basic 3-6 (MCP), Visual C++, Delphi, C# and VB.Net through years.
He has experience in practically all (technical) stages of project development, including planning, framework development, user interface, business processes, as well as testing and documenting. He has worked on big and small projects in Slovenia and abroad (e.g. participated in completing level 3 IS for the Nucor steel plant, Hertford, USA).
Currently he enjoys programming in .net environment using C#. Since 2000 he has been active in Developer Express' DX Squad and has been ECDL trainer and tester. He also gives lectures on conferences and other events in Slovenia.

Month List

Tag cloud

Most comments

Dan Dan
4 comments
ca Canada
Thomas Thomas
3 comments
de Germany
Sebastian Sebastian
1 comments
ca Canada

RecentComments

Comment RSS