Tuesday, 14 June 2011

TryGetValue Extension method for IDataReader

Ever had that situation where you have a method which will FILL your data entity with data returned from various sources (eg Stored Procedures).

Each source might push different data into the reader so you're not sure exactly which ones will be in the reader at any particular time.

So instead of hard coding things like:

            if (reader["Bonet_ID"] != DBNull.Value)
                car.BonetID = Convert.ToInt32(reader["Bonet_ID"]);

You can create an Extenstion method for the IDataReader like this:

        /// <summary>
        /// Determines if a field name exists in an IDataReader and, if so, its value is not null
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool TryGetValue(this IDataReader source, string name, out object value)
            value = DBNull.Value;

                value = source[name];
                // Do nothing because value is null already

            return (value != DBNull.Value);

And now you can change your code to do this nifty little diddy instead:

            if (reader.TryGetValue("Bonet_ID", out temp))
                car.BonetID = Convert.ToInt32(temp);

No comments:

Post a Comment