【问题标题】:How to fetch data from a datareader when there's a class inside another one?当另一个类中有一个类时,如何从数据读取器中获取数据?
【发布时间】:2016-09-21 15:18:37
【问题描述】:

我正在处理一个项目,该项目需要从数据库中获取数据,我在编写从数据读取器加载数据并使其工作的方法时遇到了一些麻烦。

在这个特定的模型中,我有这两个类,定义如下:

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

COUNTRY
private int countryId;
private string countryName;

这是我编写的代码示例,但它不起作用(意味着 Visual Studio 将其标记为错误)。我想知道有没有人能这么好心地帮我解决这个问题。

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

【问题讨论】:

  • 视觉工作室给你的错误是什么?
  • 如果您能提供有关您要求我们修复的错误的信息,这将极大地帮助我们。
  • 什么是country?我在您的代码中没有看到任何显示最初声明的位置。

标签: c# asp.net .net visual-studio


【解决方案1】:

假设你有这两个类,定义如下:

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

方法如下所示

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

您需要在分配属性之前创建Country 类的实例

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 2016-05-19
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多