Re: creating ExecuteQuery method



Marc,

Do you want to see the result?

If it is somewhere easily accessible I might take a look... I'm not
planning on jumping through any hoops...

Here is your code committed:

http://dblinq2007.googlecode.com/svn/trunk/DbLinq/Vendor/Implementation/Vendor.cs


public virtual IEnumerable<TResult>
ExecuteQuery<TResult>(DbLinq.Linq.DataContext context, string sql, params
object[] parameters)
where
TResult : new() {
using (IDbCommand command =
context.DatabaseContext.CreateCommand()) {
string sql2 = ExecuteCommand_PrepareParams(command, sql,
parameters);
command.CommandText = sql2;
command.Connection.Open();
using (IDataReader reader = command.ExecuteReader(
CommandBehavior.CloseConnection |
CommandBehavior.SingleResult)) {
if (reader.Read()) {
// prepare a buffer and look at the properties
object[] values = new object[reader.FieldCount];
PropertyDescriptor[] props = new
PropertyDescriptor[values.Length];
#if HyperDescriptor
// Using Marc Gravell HyperDescriptor gets significantly better
reflection performance (~100 x faster)
// http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx
PropertyDescriptorCollection allProps =
PropertyHelper<TResult>.GetProperties();
#else
PropertyDescriptorCollection allProps =
TypeDescriptor.GetProperties(typeof(TResult));
#endif
for (int i = 0; i < props.Length; i++) {
string name = reader.GetName(i);
props[i] = allProps.Find(name, true);
}
do { // walk the data
reader.GetValues(values);
TResult t = new TResult();
for (int i = 0; i < props.Length; i++) {
// TODO: use char type conversion delegate.
if (props[i] != null) props[i].SetValue(t, values[i]);
}
yield return t;
} while (reader.Read());
}
while (reader.NextResult()) { } // ensure any trailing
errors caught
}
}
}


1. I'm not sure about connection closing issue. Is the connection closed
immediately if yield returns last entity ?
Or should this code modified so that if last entity is returned, connection
is closed before final yield return is executed ?

2. I dont understand this:

while (reader.NextResult()) { } // ensure any trailing errors caught

Why this is required? Why to read other result sets, maybe to ignore them
silently ?
Can this line safely removed ?

Andrus.


.


Loading