Fastest way to use reflection for converting datareader to list

I am using reflection to convert datareader into the generic collection list. Can anybody
suggest me the best way to implement reflection for this? I want the fastestway?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I assume what you want to do is something like:

List<MyClass> list = LoadFromDataReader<MyClass>(dataReader);

with:

class MyClass
{
    [DataField("FirstName")] public string FirstName { get; set; }
    [DataField("LastName")] public string LastName { get; set; }
}

I do this by:

  1. Using Type.GetProperties and PropertyInfo.GetCustomAttribute to put together a dictionary mapping field names to PropertyInfo objects
  2. Calling PropertyInfo.SetValue on each field in each record

You can cache the results of step (1), since the field/property mapping isn’t going to change during the life of the application.

If performance is a problem (i.e. if step (2) turns out to be a bottleneck), then you have to avoid using reflection and generate code to set the properties directly. A couple of alternative improvements:

  • Use System.CodeDom to generate a C# class containing code to set the properties according to the respective fields on the IDataReader. Note that System.CodeDom invokes the csc.exe compiler in the background, so you need to generate this code once at startup and re-use it on each call.
  • Use System.Reflection.Emit.DynamicMethod to generate IL code that sets properties. Less runtime overhead than System.CodeDom, but since you’re generating raw IL, this is much harder to write and debug. Use as a last option.

Method 2

This really depends on exactly what you are looking at doing. I implement a object/interface process where I create information objects that hold the data that is returned. I then use an interface IFillable or something similar that passes a DR to the object and the object does the hydration from the DR.

This way I avoid the need for reflection, and the performance is great. I then have a few generic helper methods for Fill and FillCollection.

I got the idea based on stuff inside the CBO object of the DotNetNuke framework. It also implements a reflection method as well, that is fairly decent in performance.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x