Solved

reflection of database data to an object

Posted on 2003-11-20
5
258 Views
Last Modified: 2010-04-16
I was wondering if anyone knew if there was a way to instantiate an object and then that object use reflection on itself. i.e.

I instantiate an object by calling it like this.

Employee e = new Employee("someID");

then in the process of creating itself employee calls some reflection method to instantiate it's own properties.

Anyone seen this happen?  I've got an idea of how it should be done but just having a hard time figuring it all out.

I am using this article as a basis:

http://www.c-sharpcorner.com/Code/2002/April/ReflectingDataXMLTL004.asp
0
Comment
Question by:jayrod
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 6

Accepted Solution

by:
purpleblob earned 500 total points
ID: 9788900
Yes this is be possible below is an example (if this is indeed what you want to do) obviously it seems a little odd using reflection in this manner as when you write the object you'll obviously know the properties etc. , so I assume you've got some clever reason for using reflection for such a process :-)

Anyway, this will work

public class Employee
{
   private int m_Value = 0;

   public int Val
   {
      get { return m_Value; }
      set { m_Value = value; }
   }
   public MyObject(string something)
   {
      Type t = this.GetType();
      PropertyInfo[] pinfo = t.GetProperties();
      t.InvokeMember(pinfo[0].Name, BindingFlags.SetProperty, null, this, new object[]{123});
   }
}

Now if you call this from somewhere else, i.e.

Exmployee obj = new Employee("someID");
int i = obj.Val;

This will assign i the value 123 which was set via reflection within the constructor.

Hope this helps
0
 
LVL 6

Expert Comment

by:purpleblob
ID: 9788922
Whoops, sorry as I was changing the code to reflect your Employee object I forgot to alter the constructor from MyObject to Employee.
0
 
LVL 3

Author Comment

by:jayrod
ID: 9789215
The clever reason is that the properties represent field names in a database. It seems that in order to do this before I would tell the object to get the row corresponding to the object from the database and then manually set each property.  Now this works fine.. but if I changed the database table at all I had to change the code.

I was hoping to find a way to do this dynamically. I asked about this topic a few months back(before I knew anything about reflection) and I eneded up using Hashtables and ArrayLists to represent my data. But this has become way too obscure.

thank you for this code. I'm going to test it out right now :)
0
 
LVL 3

Author Comment

by:jayrod
ID: 9789582
Outstanding!!!!!

Here is the final code. This is a method that will instantiate it's own properties (mind you the properties need to have a Set parameter) with a row from the database.

string sqlString = "select * from nrlfcuDepartments where departmentID = @departmentID";
r1 = SqlHelper.ExecuteReader(connection, CommandType.Text, sqlString, new SqlParameter("@departmentID", this._departmentID));

r1.Read();
if(r1.HasRows)
{

      Type t = this.GetType();
      PropertyInfo[] pinfo = t.GetProperties();

      for(int i=0;i<r1.FieldCount;i++)
      {
            try
            {
                  string name = r1.GetName(i);
                  t.InvokeMember(
                        r1.GetName(i),
                        BindingFlags.Default | BindingFlags.SetProperty,
                        null,
                        this,
                        new object [] { r1.GetValue(i) }
                        );
            }
            catch
            {//Means that a value was null or a fieldName has been changed                                    
            }
      }
}
0
 
LVL 6

Expert Comment

by:purpleblob
ID: 9789721
Ah, I suspected it might have something to do with initiating your object from a database record :-)

I did see something rather cool on codeproject which used Attributes to say which properties should be set from the database, I think it was this on http://www.codeproject.com/cs/database/dal1.asp I only had a glancing look but you might find it useful/interesting
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question