Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Database Mapper
    text
    copied!<p>I was looking to map my database query results to strongly type objects in my c# code. So i wrote a quick and dirty helper method on the SqlConnection class which runs the query on the database and uses reflection to map the record columns to the object properties. The code is below:</p> <pre><code> public static T Query&lt;T&gt;(this SqlConnection conn, string query) where T : new() { T obj = default(T); using (SqlCommand command = new SqlCommand(query, conn)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { obj = new T(); PropertyInfo[] propertyInfos; propertyInfos = typeof(T).GetProperties(); for (int i = 0; i &lt; reader.FieldCount; i++) { var name = reader.GetName(i); foreach (var item in propertyInfos) { if (item.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) &amp;&amp; item.CanWrite) { item.SetValue(obj, reader[i], null); } } } } } } return obj; } </code></pre> <hr> <pre><code> public class User { public int id { get; set; } public string firstname { get; set; } public string lastname { get; set; } public DateTime signupDate { get; set; } public int age { get; set; } public string gender { get; set; } } var user = conn.Query&lt;User&gt;("select id,firstname,lastname from users"); </code></pre> <p>I just wanted a second opinion on my approach above of using reflection to tie the values together, if there's anything i can do better in the code above. Or if there's some other totally different approach i can take to get the same result?</p> <p>I think i can probably improve the code in the helper method by removing the loop for propertyInfos and using a dictionary instead. Is there anything else that needs to be tweaked?</p> <p>P.S: i'm aware of Dapper, i just wanted to implement something similar on my own to help me learn better.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload