Wednesday 3 August 2011

UPDATE: TryGetValue Extension method for IDataReader !Version 2!

My older post XXX detailed a pattern for retrieving values from a DataReader.

This can actually be further enhanced so that you do the Cast and Check all in one line using the power of LINQ syntax:

public static bool TryGetValue(this IDataReader source, string name, Action<object> value)
        {
            try
            {
                if (source[name] != null && source[name] != DBNull.Value)
                {
                    value(source[name]);
                    return true;
                }
            }
            catch
            {
            }

            return false;
        }

Then to call it, you do something like

reader.TryGetValue("test", x => myInt = Convert.ToInt32(x));

No comments:

Post a Comment