简体   繁体   中英

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM