I am trying to convert records from MySqlDataReader
to ObservableCollection<T>
but I always end up with exception - Unable to cast object of type 'System.Data.Common.DataRecordInternal' to type 'System.Data.IDataReader'
From Jon Skeet's answer over here and referring SLaks
comment in the same answer, I ended up writing below code but still I don't find how am getting that exception.
ObservableCollection<ColumnItems> DataList;
using (MySqlCommand cmd = new MySqlCommand(_query))
{
await Global.currentConnection.OpenAsync();
cmd.Connection = Global.currentConnection;
MySqlDataReader reader = cmd.ExecuteReader();
var dataDetails = reader.Cast<IDataReader>().Select(x => new ColumnItems
{
col1 = x["col1"] is DBNull ? null : x["col1"].ToString(),
col2 = x["col2"] is DBNull ? null : x["col2"].ToString(),
col3 = x["col3"] is DBNull ? null : x["col3"].ToString(),
col4 = x["col4"] is DBNull ? null : x["col4"].ToString()
});
DataList = new ObservableCollection<ColumnItems>(dataDetails);
//Exception while assigning data
await Global.currentConnection.CloseAsync();
}
I also tried replacing var dataDetails
with ObservableCollection<ColumnItems> dataDetails
but again failed with no luck. I ended up finding very few resources for above exception and couldn't gather much knowledge to solve this exception. How can I fill data into my ObservableCollection<T>
?
Just for karma :-) IDataReader is not IEnumerable and has no method to produce IEnumerable Fortunately, DataTable is collection of rows and can be converted to enumerable If your table is not very big
DataTable dt = new DataTable();
dt.Load(reader);
var dataDetails=dt.AsEnumerable().Select(...