[英]How to create a table with two columns that are related to the primary key of another table?
[英]How to create a DataRelation from one column in a table to two columns in another table
我有一個名為test_results
的數據test_results
其中包含以下各列:
和DataTable叫students
同列:
我想在表之間創建一個DataRelation,以便可以獲取所有test_results
行,其中
其中x是來自students
的student_id
我想這樣做,以便快速遍歷學生並找到他們的數學結果:
foreach (DataRow[] student in students){
DataRow[] mathResults = student.GetChildRows( "relation_student_math_results" );
foreach (DataRow[] mathResult in mathResults ){
// do something
}
}
初始化DataRelation非常簡單; 您可以使用基本構造函數。 就您而言,類似:
DataRelation studentResultsRelation = new DataRelation("StudentResults", students.Columns["student_id"], test_results.Columns["student_id"]);
parentDataSet.Relations.Add(studentResultsRelation);
其中parentDataSet是包含兩個數據的數據集。
但是,這有點棘手。 您不能直接查詢數據關系,因為它僅定義兩個表之間的關系。 您可以做的是:
1)找到與您想要的學生相匹配的行:
int studentId = 42;
DataRow[] studentRow = students.Select(String.Format("student_id = {0}"), studentId);
2)然后,您可以利用DataRelation來檢索所有該學生的結果:
//Assumes 1 student row matched your query! Check for 0 rows and more than 1, too!
DataRow[] studentResults = studentRow[0].GetChildRows(studentResultsRelation);
然后,您可以圍繞這些循環查找數學結果:
List<DataRow> mathResults = new List<DataRow>();
foreach(DataRow resultRow in studentResults){
if(Convert.ToString(resultRow["subject"]).Trim().ToUpper() == "MATH")
{
mathResults.Add(resultRow);
}
}
我可以看到您已經擁有了大部分功能,並且我了解了您想要處理數據關系; 但是,我不相信您可以直接使用它-相反,您首先必須在子(GetParentRow [s])或父表(GetChildRow [s])中找到所需的行,然后該關系允許您快速找到匹配的行集。 然后,您可以根據需要過濾它們。
順便說一句,這是使用數據庫查詢的簡單得多的練習。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.