我正在编写一个从数据库导入数据的程序。我想把所有这些表放在我自己的对象中。所有这些DataTable属性都被填充,直到执行Base examBase = Base()
,但在此行之后,exam.Base.Tests
不再存在。是什么原因造成的?
class Base
{
MySqlConnection myConnection;
MySqlDataAdapter testsDataAdapter;
DataTable testsDataTable;
MySqlDataAdapter questionsDataAdapter;
DataTable questionsDataTable;
MySqlDataAdapter answersDataAdapter;
DataTable answersDataTable;
public Base()
{
string myConnectionString = "Database=Exams;Data Source=localhost;User Id=root;Password=";
myConnection = new MySqlConnection(myConnectionString);
myConnection.Open();
GetTests();
GetQuestions();
GetAnswers();
}
private void GetTests()
{
string testQuery = "SELECT * FROM tests";
testsDataAdapter = new MySqlDataAdapter(testQuery, myConnection);
testsDataTable = new DataTable();
testsDataAdapter.Fill(testsDataTable);
testsDataTable.PrimaryKey = new DataColumn[] { testsDataTable.Columns["TestID"] };
this.Tests = testsDataTable;
}
private void GetQuestions()
{
string questionQuery = "SELECT * FROM questions";
questionsDataAdapter = new MySqlDataAdapter(questionQuery, myConnection);
questionsDataTable = new DataTable();
questionsDataAdapter.Fill(questionsDataTable);
this.Questions = questionsDataTable;
}
private void GetAnswers()
{
string answerQuery = "SELECT * FROM answers";
answersDataAdapter = new MySqlDataAdapter(answerQuery, myConnection);
answersDataTable = new DataTable();
answersDataAdapter.Fill(answersDataTable);
this.Answers = answersDataTable;
}
public DataTable Tests { get; set; }
public DataTable Questions { get; set; }
public DataTable Answers { get; set; }
}
首先在GetName()方法中看到异常:
class Test
{
Base examBase;
private List<Question> questions;
public Test(int testID)
{
examBase = new Base();
this.TestID = testID;
GetName();
GetDescription();
GetAuthor();
GetQuestions();
}
private void GetName()
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
好的,对象examBase.Tests
存在,但是有一些使用whis Find()
方法的东西。在我的基础上,在表格中&#34;测试&#34;我有一个主键(列TestID),但我得到了KeyMissing异常。 Meybe我错误地使用了这个Find()
?