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[] { 180,"语文"1 });
            dt2.Rows.Add(new object[] { 290"语文"2 });
            dt2.Rows.Add(new object[] { 360,"数学"1 });
            dt2.Rows.Add(new object[] { 450"数学",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"]);
                }
            }
posted @ 2012-07-10 16:31  唔愛吃蘋果  阅读(747)  评论(0编辑  收藏  举报