5
\$\begingroup\$

I'm working on a small project with dBase files from a 3rd party. Realizing that most of the code to fetch tables and form objects is the same, I made this function:

public static IEnumerable<T> OleDbFetch<T>(Func<OleDbDataReader, T> formator, string connectionString, string query)
{
 var conn = new OleDbConnection(connectionString);
 conn.Open();
 var cmd = new OleDbCommand(query, conn);
 var reader = cmd.ExecuteReader();
 while (reader.Read())
 yield return formator(reader);
 conn.Close();
}

That way I can use it with all sorts of classes (pre-made, imposed) that have mostly parameter-less constructors:

class Person
{
 public int ID { get; set; }
 public string Name { get; set; }
 public Person() { }
}
//...
var persons = OleDbFetch<Person>(
 r => new Person()
 { 
 ID = Convert.ToInt32(r["ID"]), 
 Name = r["Name"].ToString() 
 }, 
 connString, "SELECT ID, Name FROM Person");

Am I missing something obvious, being reckless, or giving myself too much trouble?

asked Nov 10, 2011 at 1:58
\$\endgroup\$
1
  • \$\begingroup\$ I guess I should secure the connection... Make sure it's open. \$\endgroup\$ Commented Nov 10, 2011 at 2:48

1 Answer 1

6
\$\begingroup\$

Dispose() of types that implement IDisposable with using blocks:

using (var conn = new OleDbConnection(connectionString))
{
 conn.Open();
 using (var cmd = new OleDbCommand(query, conn))
 using (var reader = cmd.ExecuteReader())
 {
 while (reader.Read())
 yield return formator(reader);
 }
}
answered Nov 10, 2011 at 3:08
\$\endgroup\$
1
  • \$\begingroup\$ I'm a sucker for explicitly closing connections... \$\endgroup\$ Commented Nov 10, 2011 at 3:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.