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