数据插入层次格式从一个table到另一个

Data insertion into the hierarchy format from one table to another

我在将记录从一个 table 插入另一个时遇到问题 table 的架构相同

Table 1     
Id  Parent Id   Text
11  Null          A
12  Null          B
13  11            C
14  11            D
15  13            E

记录应该以这种格式插入,我必须复制外键关系而不是它的标识。

Table 2     
Id  Parent Id   Text
31  Null         A
32  Null         B
33  31           C
34  31           D
35  33           E

你想要的在Database这边很容易实现。 但是由于您正在寻找 linq 方法。这是如何实现的。

流程分为两部分:

希望你有 Table1Table2 的模型(使用你认为有用的顺序。我认为 Table1是温度 table):

Public class myEntity
{
  public int Id{get; set;}
  public int? ParentId{get; set;}
  public string Text{get; set;}
}

1st:从 Table A 复制所有 Text 属性并将它们插入 Table B 并增加 IDs

var Table2 = new List<myEntity>();

Table1.Select(s=>s.Text).OrderBy(o=>o).ToList().ForEach(f=>
{
    //now append the texts to 
    Table2.Add(new tablesTest { Id = (Table2.Count + 1), Text = f });//remove the Id property manupulation or set it to 0 if you are inserting directly in the database and use the context.SaveChanges();(*if entity-framework*) once the insertion is complete.
}}

2nd:使用 self-join 创建映射 table 以获取 Table1Table1 中的条目之间的 parent-child 关系然后更新 Table2

中的条目
var parentChildListFromTb1 = from m in Table1
                      join ch in Table1 on m.Id equals ch.ParentId
                      select new
                      {
                         Id = ch.Id,                             
                         Parent = m.Text,
                         Text = ch.Text
                      };

这会给你一个输出:

----------------------------
|  Id  |  Parent  |  Text  |
----------------------------
|  13  |    A     |    C   |
----------------------------
|  14  |    A     |    D   |
----------------------------
|  15  |    C     |    E   |
----------------------------

现在,在我们有了 parent-child 列表之后,我们通过查询 Table2 并使用其尊重的 ID 更新其 ParentId 来创建子列表:

parentChildListFromTb1.ForEach(f=>{
            var ChildEntity = Table2.Single(s => s.Text.Equals(f.Text));//fetching the child entity from Table2
            ChildEntity.ParentId = Table2.Single(s => s.Text.Equals(f.Parent)).Id;//updating the parentIds in Table2
});

Table2 看起来像:

------------------------------
|  Id  |  ParentId  |  Text  |
------------------------------
|   1  |    null    |    A   |
------------------------------
|   2  |    null    |    B   |
------------------------------
|   3  |     1      |    C   |
------------------------------
|   4  |     1      |    D   |
------------------------------
|   5  |     3      |    E   |
------------------------------

我找到了这个问题的答案。

步骤: 将 Text 列值插入主 table,将 ParentId 保留为 null,同时将值作为 oldId 键插入 Dictionary 并将新插入的 Id 作为相应键的值插入。

插入后根据映射的字典键值对更新值