次の方法で共有


DataSet, DataTable, DataRelation, PrimaryKey template.

Sometimes I need to whip up a dataset with some tables and primary keys and relations.

It’s not hard to do, but repetitive. So, here is a template that I use. Thought I’d share it.

        static void Main(string[] args)

        {

            // Create list of columns, add/remove/rename as necessary

            List<DataColumn> tbOneCols = new List<DataColumn>();

            tbOneCols.Add(new DataColumn("tbOne_cOne", typeof(int)));

            tbOneCols.Add(new DataColumn("tbOne_cTwo", typeof(string)));

            List<DataColumn> tbTwoCols = new List<DataColumn>();

            tbTwoCols.Add(new DataColumn("tbTwo_cOne", typeof(int)));

            tbTwoCols.Add(new DataColumn("tbTwo_cTwo", typeof(int)));

            tbTwoCols.Add(new DataColumn("tbTwo_cThree", typeof(string)));

            // Create tables and insert the rows.

            DataTable tblOne = new DataTable("TableOne");

            foreach (DataColumn dc in tbOneCols)

            {

                tblOne.Columns.Add(dc);

            }

            DataTable tblTwo = new DataTable("TableTwo");

            foreach (DataColumn dc in tbTwoCols)

            {

                tblTwo.Columns.Add(dc);

            }

            // Add primary keys to datatables.

            DataColumn[] tblOnePk = new DataColumn[1];

            tblOnePk[0] = tblOne.Columns[0];

            tblOne.PrimaryKey = tblOnePk;

            DataColumn[] tblTwoPk = new DataColumn[1];

            tblTwoPk[0] = tblTwo.Columns[0];

            tblTwo.PrimaryKey = tblTwoPk;

            // Create DataSet and add tables.

            DataSet ds = new DataSet("TestDataSet");

            ds.Tables.Add(tblOne);

            ds.Tables.Add(tblTwo);

            // Add a relation to the dataset (first column in t1 to second column in t2)

            DataRelation dsRel = new DataRelation("TblOne_to_TblTwo", tblOne.Columns[0], tblTwo.Columns[1]);

            ds.Relations.Add(dsRel);

            // Finally add some rows

            tblOne.Rows.Add(new object[]{1, "value one"});

            tblOne.Rows.Add(new object[]{2, "value two"});

            tblTwo.Rows.Add(new object[] { 1, 1, "value one" });

            tblTwo.Rows.Add(new object[] { 2, 1, "value one" });

            tblTwo.Rows.Add(new object[] { 3, 1, "value one" });

            tblTwo.Rows.Add(new object[] { 4, 2, "value one" });

        }