Dynamic Class Properties from Data Row Columns

B

Brent

I can't seem to locate any easy way to create dynamic class properties.
Essentially, I want to take the column headers from a data result set,
create a property having the column header name, and then set the value
of the property to the data in the corresponding field.

For example, if I had this row from table "users":



ID Name Age

1 Barry 35
2 Brenda 33

....I could then write a SQL statement, e.g., "SELECT * from users where
ID = 2"

....and then pass it through a class

Users myuser = new Users();

that would loop through the column names, creating the properties Name
and Age (right there!) and then setting the property value by looping
through the values. Accessing the "Users" class would yield...

Users.Name = Brenda
Users.Age = 33

What I'm trying to avoid is typing out 100 column header names, and then
having to add or subtract more names as the database changes...also, I
could create classes out of any-ol'-table much easier.

I'd sure appreciate some help!

--Brent
 
R

Robbe Morris [C# MVP]

You could in .NET but it would be way too slow at runtime.
Check out the source code for the object mapper below.
It creates the classes for you at design time. A much faster
approach.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top