Jose Ignacio Radesca Jose Ignacio Radesca - 2 months ago 7
ASP.NET (C#) Question

How to fetch data from a datareader when there's a class inside another one?

I'm working on a project, which requires fetching data from a database and I'm having a bit of trouble writing the method to load the data from a datareader and making it work.

In this particular model, among others, i have these two classes, defined as follows:

AUTHOR
private string authFirstName;
private string authLastName;
private Country country;

COUNTRY
private int countryId;
private string countryName;


This is my sample of code i wrote, and it's not working (meaning that visual studio marks it as wrong). I wonder of anybody could be so kind to help me out a bit with this matter.

protected static Author LoadFromReader(IDataRecord row)
{
Author a = null;
if (row != null)
{
a = new Author
{
AuthFirstName = row.GetString(row.GetOrdinal("authName")),
AuthLastName = row.GetString(row.GetOrdinal("authLName")),
country.CountryId = row.GetInt32(row.GetOrdinal("countryID")),

};
}
return a;
}

Answer

Assuming you have these two classes, defined as follows:

public class Author
{
    public string AuthFirstName {get; set;}
    public string AuthLastName {get; set;}
    public Country Country {get; set;}
}

public class Country
{
    public int CountryId {get; set;}
    public int CountryName {get; set;}
}

The method would look like this

protected static Author LoadFromReader(IDataRecord row)
{
    Author a = null;
    if (row != null)
    {
        a = new Author
        {
            AuthFirstName = row.GetString(row.GetOrdinal("authName")),
            AuthLastName = row.GetString(row.GetOrdinal("authLName")),
            Country = new Country
            {
               CountryId = row.GetInt32(row.GetOrdinal("countryID"))
            },
        };
    }
    return a;
}

where you need to create an instance of the Country class on the before assigning properties

Comments