sqldatareader - VB.NET 2010 and MySql - handling DB NULLs for lazy people -
I want to initialize a class with data coming from MySq db. Some fields may be empty:
MySqlDataReader = ... as a slow drop in the form of new items (dr.GetInt16 (0), Dr.Getstrings (1), dr GetString (2))
Suppose the last two fields can be zero, then calling GetString on that field causes an exception.
I can definitely write the code to test for zero before getting each field:
If the string as dim field 1 (dr. IsDbNull (1)) Field 1 = 'None' or even "Other Field 1 = Dr. Getstring (1)
But if you have many fields then this is "ISS" nightmare. I
For this purpose I would like to type it more IIF write the VB function again, to avoid being inserted in such a way:
Namespace Utility Public Share Function IIf (TK) (ByVal condition as boolean, bevel iftrue t As if, byval iffalse t) as if the condition returns then if enter or return iffalse end even Roh
so that I can write something:
dim item as new item (dr.GetInt16 (0), util.iif (Dr. IIf was typed, "ISDBB (1)," ", Dr.Getstrings (1), Util.IIF (Dr. ISDBANL (2)," "
Works well in other cases, but unfortunately this is not in this example, because This is not a common function and not a language keyword , visiting each parameter inpout call Is evaluated, and when the field is raised no exception.
Can you think of an elegant if- less solution?
First of all, I recommend you use an ORM map - per-click here. There are very few cases where you have to do manual "mapping" nowadays
If this is one of these cases, I will use the name of the field instead of indexed when you access the data reader Do recommend.
And to answer your basic question: Try the extension methods C #, but sorry for the VB.NET syntax drive me crazy:
public Static Class DbDataReaderExtensions {public static T GetField & LT; T & gt; (The DbDataReader dbDataReader, string FIELDNAME, T DefaultValue) {if (dbDataReader .IsDBNull (FIELDNAME)) DefaultValue Return; Return (t) dbDataReader [fieldName]; }}
Comments
Post a Comment