EDIT:
A stored procedure returns the following data:
| Name | Value |
|---------|-----------|
| Member1 | someValue |
| Member2 | someValue |
And I have a class that with properties that have a custom attribute that matches the "Name" field in the database
class example{
[CustomMapping(DBName="Member1",...)]
public string MyName1{get; set;}
[CustomMapping(DBName="Member2",...)]
public int MyName2{get; set;}
}
And I have the following method to populate the class from DB:
public void LoadFromDataReader(IDataReader reader)
{
Type type = this.GetType();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo property in props)
{
CustomMappingAttribute mappingAttribute = (CustomMappingAttribute)Attribute.GetCustomAttribute(property, typeof(CustomMappingAttribute));
object val = null;
if (property.GetType() == typeof(string))
{
val = CustomObjectData.SafeRead<string>(mappingAttribute.DBName, reader, string.Empty);
}
else
{
val = CustomObjectData.SafeRead<int>(mappingAttribute.DBName, reader, int.MinValue);
}
property.SetValue(property, val);
}
}
I want to assign each property its corresponding value from the DB. The code above will not do that accurately as it will overwrite some property every time LoadFromDataReader()
is called because of the for loop.
How do I go about doing this?
FYI: CustomObjectData.SafeRead reads the fieldName from the DB and assigns it to the property.
SafeRead<T>(string fieldName, IDataReader reader, T defaultValue);
.
.
.
.
.
Old Question:
I want to create a class that is populated from the database. The class members as well as their values are to be read from the database.
A stored procedure returns the following data:
| Name | Value |
|---------|-----------|
| Member1 | someValue |
| Member2 | someValue |
Now I want my class to have the following structure read/loaded from the stored procedure:
class example{
public string Member1{get; set;}
public string Member2{get; set;}
}
There will always be a row returned, and the stored procedure could return any number of Key/Value pairs.
Is this possible? Is there a better way to do it?
I want to do this because I will be serializing this class to JSON. And this becomes trivial to do if I have the class structured correctly.