Ответ 1
Вам не хватает базового синтаксиса С#.
Data = reader;
// You cant do this. You have to loop the reader to get the values from it.
// If you simply assign reader object itself as the data you wont be
// able to get data once the reader or connection is closed.
// The reader is typically closed in the method.
Data = reader.Cast<dynamic>;
// You should call the Cast method. And preferably execute the resulting query.
// As of now you're merely assigning method reference to a variable
// which is not what you want.
// Also bear in mind that, as I said before there no real benefit in casting to dynamic
Data = reader.Cast<IEnumerable<dynamic>>;
// Cast method itself returns an IEnumerable.
// You dont have to cast individual rows to IEnumerable
Data = reader.Cast<IEnumerable<string>>;
// Meaningless I believe.
// The data you get from database is not always strings
Основная ошибка, которую вы делаете, - не вызов метода. Это то, что вы хотите:
Data = reader.Cast<IDataRecord>().ToList();
^^ // notice the opening and closing parentheses
Вы можете сделать это несколькими способами в зависимости от того, что легче обрабатывать (например, для отображения в интерфейсе).
-
Запись данных о возврате.
public IEnumerable<IDataRecord> SelectDataRecord() { .... using (var reader = cmd.ExecuteReader()) foreach (IDataRecord record in reader as IEnumerable) yield return record; //yield return to keep the reader open }
-
Возврат ExpandoObjects. Возможно, это то, что вы хотели?
public IEnumerable<dynamic> SelectDynamic() { .... using (var reader = cmd.ExecuteReader()) { var names = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList(); foreach (IDataRecord record in reader as IEnumerable) { var expando = new ExpandoObject() as IDictionary<string, object>; foreach (var name in names) expando[name] = record[name]; yield return expando; } } }
-
Последовательность возврата пакета свойств
public IEnumerable<Dictionary<string, object>> SelectDictionary() { .... using (var reader = cmd.ExecuteReader()) { var names = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList(); foreach (IDataRecord record in reader as IEnumerable) yield return names.ToDictionary(n => n, n => record[n]); } }
-
Возвращаемая последовательность массива простых объектов
public IEnumerable<List<object>> SelectObjectArray() { .... using (var reader = cmd.ExecuteReader()) { var indices = Enumerable.Range(0, reader.FieldCount).ToList(); foreach (IDataRecord record in reader as IEnumerable) yield return indices.Select(i => record[i]).ToList(); } }
-
Строки возвращаемых данных
public IEnumerable<DataRow> SelectDataRow() { .... using (var reader = cmd.ExecuteReader()) { var table = new DataTable(); table.BeginLoadData(); table.Load(reader); table.EndLoadData(); return table.AsEnumerable(); // in assembly: System.Data.DataSetExtensions } }
-
И последнее, но не менее важное: если это поможет, вы можете вернуть строго типизированную последовательность без какой-либо ручной сантехники. Вы можете использовать деревья выражений для компиляции кода во время выполнения. См. этот, например,