我正在处理一个项目,该项目需要从数据库中提取数据,而且我在编写方法时会遇到一些麻烦,无法从数据加载器加载数据并使其正常工作。
在这个特定的模型中,我有这两个类,定义如下:
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;
}
答案 0 :(得分: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
类的实例