I had the same question, and I found two common answers:
- Field alias in your SQL
- Use integer index for column
I didn't like any of these options, so I created a third: GetNthOrdinal.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
public static class SqlDataReaderExtensions
{
public static int GetNthOrdinal(this SqlDataReader reader, string columnName, int nthOccurrence = 1)
{
DataTable schema = reader.GetSchemaTable();
var occurrences = schema.Rows.Cast<DataRow>().Where(r => string.Equals((string)r["ColumnName"], columnName, StringComparison.Ordinal));
var occurrence = occurrences.Skip(nthOccurrence - 1).First();
return (int)occurrence["ColumnOrdinal"];
}
}
:
reader.GetNthOrdinal("Id", 2);
, n- 0; 1.