값을 자신을 읽는 코드에서 별칭 이름을 사용할 수 있습니다 귀하의 요청에 별칭 이름을 지정하고 나는 두 가지를 발견 일반적인 대답했다 : 당신의 SQL에
이 옵션 중 하나가 마음에 들지 않아서 세 번째를 작성했습니다. 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)
{
// Get the schema which represents the columns in the reader
DataTable schema = reader.GetSchemaTable();
// Find all columns in the schema which match the name we're looking for.
// schema is a table and each row is a column from our reader.
var occurrences = schema.Rows.Cast<DataRow>().Where(r => string.Equals((string)r["ColumnName"], columnName, StringComparison.Ordinal));
// Get the nthOccurrence. Will throw if occurrences is empty.
// reader.GetOrdinal will also throw if a column is not present, but you may want to
// have this throw a more meaningful exception
var occurrence = occurrences.Skip(nthOccurrence - 1).First();
// return the ordinal
return (int)occurrence["ColumnOrdinal"];
}
}
사용법 :
reader.GetNthOrdinal("Id", 2);
그것은 n 번째 발생이 0이 기반이 아닌 것을주의하는 것이 중요합니다; 1 시부 터 시작합니다.
왜 이름이 필요합니까? 당신은'reader.GetInt32 (0)'과'reader.GetInt32 (1)'을 사용할 수 있습니다. –