Nuts
Nuts

Reputation: 2813

Reading database table into a .NET object of different structure

I have inflation rates stored in a database with the following structure:

Database schema and sample data

When reading the above data, I need to initialize business objects with a different structure dynamically and fill them with the database data.

If the database would be like the above, I would need to create two objects: "UK Inflation Forecast" and "Germany Inflation Forecast". In this case, both objects would have 6 properties: CountryName (as String) and 5 inflation values (as Double).

Business objects

How can I create the object classes without knowing the number of properties needed and how do I fill these with data?

Upvotes: 0

Views: 115

Answers (2)

gurerkerem
gurerkerem

Reputation: 1

@user2143213 you can use linq or ADO.NET data reader.

Upvotes: 0

M P
M P

Reputation: 2337

I would say create a class of the following structur:

public class InflationClass
{
    public InflationClass()
    {
        InflationValues = new Dictionary<int, double>();
    }

    public string Country { get; set; }
    public Dictionary<int, double> InflationValues { get; private set; }
}

And load the data like so

int sampleYear = 2016;
double sampleValue = 123456789.01;

var inflation = new InflationClass();

if(!inflation.InflationValues.ContainsKey(sampleYear ))
{
    inflation.InflationValues.Add(sampleYear , sampleValue);
}

I've used C# but this can easily be converted to VB.NET if you prefer.

Upvotes: 1

Related Questions