DataSet设置关系,级联更新、删除,
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("id", typeof(int));
dt1.Columns.Add("Name", typeof(string));
dt1.PrimaryKey = new DataColumn[]
{
dt1.Columns["id"]
};
DataTable dt2 = new DataTable();
dt2.Columns.Add("id", typeof(int));
dt2.Columns.Add("Mark", typeof(int));
dt2.Columns.Add("Course", typeof(String));
dt2.Columns.Add("stuID", typeof(int));
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
//创建关系
DataRelation rel=
ds.Relations.Add(dt1.Columns["id"], dt2.Columns["stuID"]);
//获取关系的外键
ForeignKeyConstraint fkc=rel.ChildKeyConstraint;
//设置级联规则
fkc.UpdateRule = Rule.None;
fkc.DeleteRule = Rule.None;
dt1.Rows.Add(new object[] { 1, "张三" });
dt1.Rows.Add(new object[] { 2, "李四" });
dt2.Rows.Add(new object[] { 1, 80,"语文", 1 });
dt2.Rows.Add(new object[] { 2, 90, "语文", 2 });
dt2.Rows.Add(new object[] { 3, 60,"数学", 1 });
dt2.Rows.Add(new object[] { 4, 50, "数学",2 });
foreach (DataRow dr in dt1.Rows)
{
Console.WriteLine(dr["Name"]);
/*GetChildRows方法用于获取与该行数据关联的子表数据
*与其相关的还有*/
foreach (DataRow cdr in dr.GetChildRows(rel))
{
Console.WriteLine("{0}:{1}",
cdr["Course"], cdr["Mark"]);
}
}
DataTable dt1 = new DataTable();
dt1.Columns.Add("id", typeof(int));
dt1.Columns.Add("Name", typeof(string));
dt1.PrimaryKey = new DataColumn[]
{
dt1.Columns["id"]
};
DataTable dt2 = new DataTable();
dt2.Columns.Add("id", typeof(int));
dt2.Columns.Add("Mark", typeof(int));
dt2.Columns.Add("Course", typeof(String));
dt2.Columns.Add("stuID", typeof(int));
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
//创建关系
DataRelation rel=
ds.Relations.Add(dt1.Columns["id"], dt2.Columns["stuID"]);
//获取关系的外键
ForeignKeyConstraint fkc=rel.ChildKeyConstraint;
//设置级联规则
fkc.UpdateRule = Rule.None;
fkc.DeleteRule = Rule.None;
dt1.Rows.Add(new object[] { 1, "张三" });
dt1.Rows.Add(new object[] { 2, "李四" });
dt2.Rows.Add(new object[] { 1, 80,"语文", 1 });
dt2.Rows.Add(new object[] { 2, 90, "语文", 2 });
dt2.Rows.Add(new object[] { 3, 60,"数学", 1 });
dt2.Rows.Add(new object[] { 4, 50, "数学",2 });
foreach (DataRow dr in dt1.Rows)
{
Console.WriteLine(dr["Name"]);
/*GetChildRows方法用于获取与该行数据关联的子表数据
*与其相关的还有*/
foreach (DataRow cdr in dr.GetChildRows(rel))
{
Console.WriteLine("{0}:{1}",
cdr["Course"], cdr["Mark"]);
}
}