如何将数据表转换为相关数据集

问题描述 投票:0回答:4

我在数据表中对数据进行了非规范化。

数据包含员工姓名以及他们在一系列薪资周期内获得的薪资。即:

我的数据表包含:

Employee 1    Jan-1-2012     $100
Employee 2    Jan-1-2012     $300
Employee 1    Feb-1-2012     $400
Employee 2    Feb-1-2012     $200
Employee 1    Mar-1-2012     $150
Employee 2    Mar-1-2012     $325

如何将此数据加载到父数据表包含员工姓名、子数据表包含工资详细信息的数据集中?

c# datatable dataset
4个回答
21
投票

DataSet只不过是DataTable的集合。因此,要将 dataTable“加载”到 dataSet 中,只需添加它:

DataTable employees = new DataTable();
DataTable payCheckes = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(employees);
ds.Tables.Add(payCheckes);

您想以某种方式“组合”数据表吗? 拿到每个员工的工资吗?


4
投票

无需手动插入的代码:

       DataSet ds = new DataSet();
        DataTable dtemploye = new DataTable();
        DataTable dtpayment = new DataTable();

        ds.Tables.AddRange(new DataTable[] { dtemploye, dtpayment });
        DataColumn dcIdemploye = dtemploye.Columns["ID_EMPLOYEE"];
        DataColumn dcIdemployeprice = dtpayment.Columns["ID_EMPLOYEE"];
        DataRelation drrelation = new DataRelation("relemploy_payment", dcIdemploye, dcIdemployeprice);
        ds.Relations.Add(drrelation);

1
投票
      DataSet ds = new DataSet();
        DataTable dtemploye = new DataTable();
        DataColumn dcnameemploye = new DataColumn();
        DataColumn dcIdemploye = new DataColumn();
        dtemploye.Columns.AddRange(new DataColumn[]{dcnameemploye,dcIdemploye});

        DataTable dtpayment = new DataTable();
        DataColumn dtprice = new DataColumn();
        DataColumn dtDate = new DataColumn();
        DataColumn dcIdemployeprice = new DataColumn();
        dtpayment.Columns.AddRange(new DataColumn[]{dcIdemployeprice,dtprice,dtDate});

        DataRow drrowemploy = dtemploye.NewRow();
        drrowemploy[0] = "1";
        drrowemploy[1] = "Employee 1";
        dtemploye.Rows.Add(drrowemploy);

        DataRow drrowpayment = dtpayment.NewRow();
        drrowpayment[0] = "1";
        drrowpayment[0] = "01/01/2012";
        drrowpayment[1] = " 300";


        ds.Tables.AddRange(new DataTable[]{dtemploye, dtpayment});

        DataRelation drrelation = new DataRelation("relemploy_payment", dcIdemploye, dcIdemployeprice);
        ds.Relations.Add(drrelation);

0
投票
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            dt.TableName = "Table1";
            dt.Columns.Add("Sno", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Address",typeof(string));
            DataRow Dr = dt.NewRow();

            Dr["Sno"] = 1;
            Dr["Name"] = "Test";
            Dr["Address"] = "Test1";

            dt.Rows.Add(Dr);

            ds.Tables.Add(dt);
© www.soinside.com 2019 - 2024. All rights reserved.