Re: creating ExecuteQuery method
- From: Marc Gravell <marc.gravell@xxxxxxxxx>
- Date: Tue, 18 Mar 2008 14:50:55 -0700 (PDT)
You just love to set challenges ;-p
How about the following (which should work on 2.0)... if you are doing
this lots, then look for HyperDescriptor to get significantly better
reflection performance (~100 x faster) - the only thing you'd need to
change in the code would be to add the
TypeDescriptionProviderAttribute, or call
HyperTypeDescriptionProvider.Add... the latter works well if added in
a static ctor (perhaps as part of Read<T>)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeID { get; set; }
public DateTime BirthDate { get; set; }
}
static class Program
{
[STAThread]
static void Main()
{
foreach (Employee emp in Read<Employee>("SELECT FirstName,
LastName FROM Employees"))
{
Console.WriteLine("{0} {1}", emp.FirstName, emp.LastName);
}
}
const string CS = @"Data Source=datachange;Initial
Catalog=Northwind;Integrated Security=True";
static IEnumerable<T> Read<T>(string command) where T : new()
{
using (SqlConnection conn = new SqlConnection(CS))
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = command;
conn.Open();
using (SqlDataReader reader =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (reader.Read())
{
// prepare a buffer and look at the properties
object[] values = new object[reader.FieldCount];
PropertyDescriptor[] props = new
PropertyDescriptor[values.Length];
PropertyDescriptorCollection allProps =
TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < props.Length; i++)
{
props[i] = allProps.Find(reader.GetName(i),
true);
}
do
{ // walk the data
reader.GetValues(values);
T t = new T();
for (int i = 0; i < props.Length; i++)
{
if (props[i] != null) props[i].SetValue(t,
values[i]);
}
yield return t;
} while (reader.Read());
}
while (reader.NextResult()) { } // ensure any trailing
errors caught
}
}
}
}
.
- Follow-Ups:
- Re: creating ExecuteQuery method
- From: Marc Gravell
- Re: creating ExecuteQuery method
- References:
- creating ExecuteQuery method
- From: Andrus
- creating ExecuteQuery method
- Prev by Date: Web Service Dataset to a Internal SQL Server
- Next by Date: Re: C# and multimethods
- Previous by thread: creating ExecuteQuery method
- Next by thread: Re: creating ExecuteQuery method
- Index(es):
Relevant Pages
|
Loading