Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't just test reader["field"] for null or DBNull because a IndexOutOfRangeException is thrown if the column isn't in the reader.</p> <p>The code I use in my mapping layer for creating domain objects and the stored procedures that use the mapping layer might have different column names is below; you could modify it to not throw an exception if the column isn't found and return default(t) or null.</p> <p>I understand this isn't the most elegant or optimal solution (and really, if you can avoid it then you should), however, legacy stored procedures or Sql queries might warrant a work-around.</p> <pre><code> /// &lt;summary&gt; /// Grabs the value from a specific datareader for a list of column names. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Type of the value.&lt;/typeparam&gt; /// &lt;param name="reader"&gt;Reader to grab data off of.&lt;/param&gt; /// &lt;param name="columnNames"&gt;Column names that should be interrogated.&lt;/param&gt; /// &lt;returns&gt;Value from the first correct column name or an exception if none of the columns exist.&lt;/returns&gt; public static T GetColumnValue&lt;T&gt;(IDataReader reader, params string[] columnNames) { bool foundValue = false; T value = default(T); IndexOutOfRangeException lastException = null; foreach (string columnName in columnNames) { try { int ordinal = reader.GetOrdinal(columnName); value = (T)reader.GetValue(ordinal); foundValue = true; } catch (IndexOutOfRangeException ex) { lastException = ex; } } if (!foundValue) { string message = string.Format("Column(s) {0} could not be not found.", string.Join(", ", columnNames)); throw new IndexOutOfRangeException(message, lastException); } return value; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload