C# 如何将数据表转换为相关数据集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11710760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a datatable to a related dataset
提问by MillinMo
I have denormalized data in a DataTable.
我在 DataTable 中有非规范化数据。
The data contains employee names, and the pay they got over a series of pay cycles. i.e.:
数据包含员工姓名,以及他们在一系列薪酬周期中获得的薪酬。IE:
My DataTable contains:
我的数据表包含:
Employee 1 Jan-1-2012 0
Employee 2 Jan-1-2012 0
Employee 1 Feb-1-2012 0
Employee 2 Feb-1-2012 0
Employee 1 Mar-1-2012 0
Employee 2 Mar-1-2012 5
How can load this data into a DataSet where the parent DataTable contains the employees name, and the child DataTable contains details of the paycheck?
如何将此数据加载到父 DataTable 包含员工姓名、子 DataTable 包含薪水详细信息的 DataSet 中?
回答by Mitja Bonca
DataSet is nothing but a collection of DataTables. So to "load" the dataTable into dataSet simple Add it:
DataSet 只不过是 DataTable 的集合。所以要将数据表“加载”到数据集中简单添加它:
DataTable employees = new DataTable();
DataTable payCheckes = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(employees);
ds.Tables.Add(payCheckes);
Do you want to "combine" datatables somehow? Get paycheckes of each employee?
你想以某种方式“组合”数据表吗?获得每个员工的薪水?
回答by Hassan Boutougha
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);
回答by Hassan Boutougha
the code without manual insert:
没有手动插入的代码:
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);

