Wayne Phipps
Wayne Phipps

Reputation: 2069

Dynamically create object from SQL data

I've been thinking about creating objects dynamically using data stored in a database. I've done something similar in the past by serializing all the properties of each object but that was a few years ago and times have changed.

I actually like the method outlined in the answer to the following question: How to do dynamic object creation and method invocation in .NET 3.5

I'm wondering if it's possible to take this one step further and set all the properties of the object using stored data.

Obviously I could set each of the properties individually IE:
Person p = new Person();
p.Name = "Me";
p.Age = 31;

Would it be possible to do something more in-line (sorry don't quite know what this is called) like Person p = new Person() { Name = "Me", Age = 31 }; where the Name = "Me", Age = 31 properties or string could originate from a database??

Any thoughts?

Upvotes: 2

Views: 9291

Answers (2)

L.B
L.B

Reputation: 116118

Assuming you read the values from DB and put in a dictionary like:

Dictionary<string, string> parameters = new Dictionary<string, string>()
{
    {"Name","Scott"},
    {"Age","30"}
};

(See the dictionary's type: string, string But Age is int in fact)

You can dynamically create your object as

var obj = Activator.CreateInstance(Type.GetType("SO.Form2+Person"));

foreach (var pi in obj.GetType().GetProperties())
{
    pi.SetValue(obj, Convert.ChangeType(parameters[pi.Name], pi.PropertyType));
}

--

public class Person
{
    public string Name { set; get; }
    public int  Age { set; get; }
}

Upvotes: 1

Derek
Derek

Reputation: 8628

Have you thought about using LINQ to SQL? It takes all the tables of your SQL database and converts them to c# classes. You access all your data via a DataContext object, each table becomes a class you can call / edit / Update via LINQ.

Read up on the following material. There are many examples out there on the net.

http://msdn.microsoft.com/en-us/library/bb425822.aspx

I hope this helps.

Upvotes: 2

Related Questions