问题
I would like to know if there is any way to fill ObservableCollection directly from SQL server. Currently I am loading my data into DataTable (using sqlDataAdapter) and do a conversion to ObservableCollection manually and it very inefficient.
How it can be done?
回答1:
OK, I have found a way to do this:
It can be done using SqlDataReader.
public ObservableCollection<DataItem> LoadCategoriesData()
{
Command = new SqlCommand(StoredProcedure, Connection);
Command.CommandType = CommandType.StoredProcedure;
ObservableCollection<DataItem> myColl = new ObservableCollection<DataItem>();
Connection.Open();
SqlDataReader reader = Command.ExecuteReader();
while (reader.Read())
{
int mainCatID = reader.GetInt32(0);
string categoryName = reader.GetString(1);
//adding row data to observable
myColl.Add(new DataItem(mainCatID, categoryName));
}
Connection.Close();
return myColl;
}
来源:https://stackoverflow.com/questions/14179967/fill-observablecollection-directly-from-sql-server