HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

OLEDB table fetching function in C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fetchingoledbfunctiontable

Problem

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 OleDbFetch(Func 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(
    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?

Solution

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);
    }
}

Code Snippets

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);
    }
}

Context

StackExchange Code Review Q#5938, answer score: 6

Revisions (0)

No revisions yet.