如何将数据整合到表中c#SQL

时间:2018-09-19 02:19:25

标签: c# sql-server import consolidation

我有XML数据,可以通过xml阅读器将其读入数据集中。

生成的表具有几种关系,但大多数是父节点到子节点。

我计划每天读取多个文件,并将这些文件合并到sql服务器中。它们很容易被其他系统利用的地方。

考虑XML文件,例如,每个节点的子节点都有连续的ID

<main mainGUID='BlahWeSayItIsUnique' stuff type=1>
   <children thingy Number> 
      <child other things>
      <child other things>

Children将获得children_Id作为主键,child将获得children_id作为关系,并将其自己的child_Id作为主键。这些数字在1 ... n中是连续的,因此每个xml文件中肯定会重复这些id值。

那么在不复制id的情况下插入数据的正确方法是什么? 我是否要获取sql服务器最后插入的id值,然后修改内存中c#datatable中存在的数据表,然后将其插入sql中?

还是有更好的方法,例如使用根节点中的GUID进行版本控制的方法?

编辑: 我从外部来源接收xml文件,它们随数据一起提供。 我将这些XML文件读入一个数据集,该数据集基本上提供了8个表,并且这些表中的行是顺序的,并且基于此顺序号,这些表彼此相关。

已经为数据分配了顺序ID,那么如何在不复制先前导入的xml文件的情况下将这些记录插入SQL数据库?

1 个答案:

答案 0 :(得分:0)

您应该在每个id列上都具有标识。当您插入记录时,数据库将为您生成新的唯一ID。您可以读取id的值,并使用此新值更新所有引用。看起来像这样

DataSet dataSet = new DataSet();

ParentDataTable parentTable = dataSet.Parent;
ParentTableAdapter parentAdapter = new ParentTableAdapter();
ParentRow parentRow = parentTable.NewParentRow();
parentRow.p_id = -1;
parentRow.p_name = "Best parent";
parentTable.AddParentRow(parentRow);
parentAdapter.Update(parentTable);            

ChildDataTable childTable = dataSet.Child;
ChildTableAdapter childAdapter = new ChildTableAdapter();
ChildRow childRow = childTable.NewChildRow();
childRow.ch_id = -1;                         
childRow.ch_name = "Best child";            

childRow.ch_parent = parentRow.p_id;
or
childRow.ParentRow = parentRow;

childTable.AddChildRow(childRow);
childAdapter.Update(childRow);

将id设置为负值是一种处理冲突的方法。您必须一次以正确的顺序更新一张表。我个人将离开数据集并使用datacontext。看起来像

var parent = new Parent()
{
    p_name = "Best parent"
};
var child = new Child()
{
    ch_name = "Best child",
    Parent = parent
};

using (var dc = new DataContext())
{
    dc.Parents.InsertOnSubmit(parent);
    dc.Childs.InsertOnSubmit(child);
    dc.SubmitChanges();
}