Intitialzing一個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);
}
}
I C看到你已經掌握了大部分的內容,並且我明白你想要處理數據關係。然而,我不相信你可以直接使用它 - 相反,你首先必須在子類(GetParentRow [s])或父表(GetChildRow [s])中找到你想要的行,然後這個關係允許你快速找到匹配的一組行。您可以根據需要過濾這些內容。
另外,這是一個簡單得多的數據庫查詢練習。
希望這會有所幫助!
使用GetChildRows和數據關係比Select查詢快得多,當我使用student_id上的簡單連接對其進行測試時 – Vaughan
如上例所示利用子關係應該足夠快嗎?如果你願意,你可以隨時將這些信息存儲爲一組鏈接列表,或者甚至是由學生ID鍵入的字典。出於興趣,當您提到select查詢時,您是指數據庫還是數據表? – dash
這些表格是我的實際代碼的簡化,速度非常重要。 students.Select(String.Format(「student_id = {0}」),studentId)比使用DataRelation和students.GetChildRows(...)慢很多。獲得一個關係學生的所有測試結果,然後查詢「數學」測試的速度要快得多。在OP中,我想知道這是否可以在一個關係中完成。 – Vaughan