Skip to content
wade.one

wade.one

wade womersley – york based software engineer

  • Home
  • 2013
  • September
  • 18
  • C# MySqlDataReader – “one line” function to return a row as an instance of a class.

C# MySqlDataReader – “one line” function to return a row as an instance of a class.

Posted on September 18, 2013October 4, 2013 By Wade 1 Comment on C# MySqlDataReader – “one line” function to return a row as an instance of a class.
Programming

MySql in C# is rather painless using the MySQL Connector for .net, but one thing it is missing is a no-frills, no extra requirements, no pre-defined ERD return a row as an instance of a class function. Coming from a PHP background, I love the PDO function fetchObject(), it’s just right there and you get an object you can handle.

I really wanted this functionality in my code to not only make it easier to read, but also make types easier to manage when returned from MySQL – why do I need to call GetString() or GetInt() when I can just say “look, the row that returns will look like this, return me an object with the properties set”.

So I wrote a static extension function:

/// <summary>
/// Grabs an instance of a class directly from the MySqlDataReader instead of manually building from GetString() etc.
/// </summary>
/// <typeparam name="T">Type of object to return</typeparam>
/// <param name="reader">Reader instance</param>
/// <returns>new T</returns>
public static T GetObject<T>(this MySql.Data.MySqlClient.MySqlDataReader reader)
{
    var obj = Activator.CreateInstance(typeof(T));
    var fields = obj.GetType().GetFields();

    foreach (var field in obj.GetType().GetFields())
    {
        var attrs = field.GetCustomAttributes(typeof(System.Runtime.Serialization.DataMemberAttribute), true) as System.Runtime.Serialization.DataMemberAttribute[];

        if (attrs.Length == 0)
        {
            continue;
        }

        var fieldID = attrs[0].Name;
        var fieldType = field.FieldType;

        field.SetValue(obj, reader.GetValue(reader.GetOrdinal(fieldID)));
    }

    return (T)obj;
}

This allows me to do something along the lines of reader.getObject<MyClass>() where MyClass would look something like this:

class MyClass
{
    [DataMember(Name = "id")]
    public int ID;

    [DataMember(Name = "email")]
    public string Email;

    [DataMember(Name = "full-name")]
    public string FullName;
}

et voila, you’ve got an instance of MyClass where the MySQL columns are mapped to friendly properties on your object and the type hint makes it all clear as to what it is.

As you can see, I’ve used the DataMember properties to define the SQL column name the data would come from, allowing the 1-1 mapping of SQL column to C# property.

Now there are optimisations to be add here, I do not contest that, using reflection can slow things down a bit, caching would be a good idea for example. But this works perfectly for me and means rather than 3 lines:
obj.ID = GetInt(“id”);
obj.Email = GetString(“email”);
obj.FullName = GetString(“full-name”);
I now just have one clean line that uses the object I would have already used and populated manually.

Share:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X
  • Click to share on Tumblr (Opens in new window) Tumblr
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Reddit (Opens in new window) Reddit

Related

Comments

comments

Post navigation

❮ Previous Post: Cloudant’s Rather Awesome dbcopy for re-reducing the output of existing map/reduce data.
Next Post: phantomjs custom module – require and create ❯

You may also like

Programming
MongoDB vs DocumentDB
March 26, 2023
Ego-centric
Today’s musings
September 3, 2009
Programming
Another day, another group of PHP “funness”
September 2, 2009
Programming
PHP5.4.3 Available on Dotdeb.org (Installs fine on Ubuntu)
May 22, 2012

One thought on “C# MySqlDataReader – “one line” function to return a row as an instance of a class.”

  1. Krzysztof says:
    June 9, 2014 at 16:42

    Nice solution!

    1) I think fields can be used in foreach()
    2) fieldType is not used, but I used it to cast DBNull in case of string type to empty string. Something like

    var chunk = reader.GetValue(reader.GetOrdinal(fieldID))
    if chunk ==DBNull && fieldType == typeof(string) chunk = string.empty;

    Log in to Reply

Leave a Reply Cancel reply

You must be logged in to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • AI
  • artificial intelligence
  • Ego-centric
  • Events
  • Films
  • Food
  • Gaming
  • Gym
  • Hardware
  • Holidays
  • News
  • PHP
  • Programming
  • Random Stuff
  • Reviews
  • Science
  • SEO
  • Software
  • Software Engineer
  • Support
  • Uncategorized
  • Work

Copyright © 2025 wade.one.

Theme: Oceanly News Dark by ScriptsTown