I want to use ExecuteReader with CommandBehavior to collect data from an SQL table along with PrimaryKey information for that table.
I only know how to do one or the other. If I specify the CommandBehavior to collect KeyInfo, then Data is not collected. If I use the default and collect Data, KeyInfo is not collected.
DataTable Collect(string tableName) {
DataTable table = new DataTable(tableName);
if (!String.IsNullOrEmpty(tableName)) {
using (SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM " + tableName, new SqlCeConnection(Connection))) {
cmd.Connection.Open();
// this line will collect the Primary Key information: (Rows.Count = 0)
table.Load(cmd.ExecuteReader(CommandBehavior.KeyInfo));
// this line will collect the Row Data:
table.Load(cmd.ExecuteReader());
// I know the using clause is supposed to do this, but it can take too long
cmd.Connection.Close();
}
}
return table;
}
I have attempted to collect both by using both flags:
CommandBehavior cb = CommandBehavior.Default | CommandBehavior.KeyInfo
table.Load(cmd.ExecuteReader(cb));
However, this still results in 0 DataRows being returned.
I could, of course, make two (2) calls and merge the data – but is this necessary? Is there nothing cleaner?
The integer value of
CommandBehavior.Defaultis zero. This is why thisCommandBehavior.Default | CommandBehavior.KeyInfois no different than justCommandBehavior.KeyInfoHowever calling
CommandBehavior.KeyInfois only supposed to add information to the schema and not effect the rows returned as it does with the OleDb and SqlClients.I’m guessing this is specific to the SqlCe objects.