我有以下数据结构
List<Items> items = new List<Items>();
items.Add(new Item()
{
P1 = "P1",
P2 = "P2",
P3 = "P3",
P4 = new List<P4>
{
new P4() {T1 = 1, T2 = "test", T3 = 1, T4 = 1},
new P4() {T1 = 2, T2 = "test", T3 = 2, T4 = 2},
}
});
items.Add(new Item()
{
P1 = "P11",
P2 = "P12",
P3 = "P13",
P4 = new List<P4>
{
new P4() {T1 = 3, T2 = "test", T3 = 3, T4 = 1},
new P4() {T1 = 4, T2 = "test", T3 = 3, T4 = 1},
}
});
我有GetData()
方法返回上面的数据结构/数据。
问题
我有三张桌子
Table 1 columns are: P1, P2, P3
Table 2 columns are: T1 and T2, (P1 FK)
Table 3 columns are: T3, T4 (T1 FK)
我不知道如何转换/拆分我的上述数据结构来存储它 进入以上三个表?
我的尝试
创建class.cs
public class DTO
{
public list<table1> table 1 {get; set;}
}
public class table 1
{
public string P1 {get; set;}
public string P2 {get; set;}
public string P3 {get; set;}
public list<tabl2>
}
public class table 2
{
public string t1 {get; set;}
public string t2 {get; set;}
public list<t3>
}
public class table 3
{
public string t3 {get; set;}
public string t4 {get; set;}
}
查询 尝试了一些查询,但无法成功
Dto dto = new Dto();
var data = GetData();
foreach(item it in data)
{
dto.table1.add(new table1
{
p1 = it.p1,
p2 = it.p2,
p3 = it.p3
t1 // not sure how i populate this since it is expecting list
})
}
答案 0 :(得分:1)
不打磨版。但是如下所示:
var tables = new List<Table1>();
foreach (var item in items)
{
var t1 = new Table1
{
P1 = item.P1,
P2 = item.P2,
P3 = item.P3,
Table2s = new List<Table2>()
};
var p4Group = item.P4s.GroupBy(pt => new {pt.T1, pt.T2 });
foreach (var p4 in p4Group)
{
var table2 = new Table2
{
T1 = p4.Key.T1,T2 = p4.Key.T2, Table3s = new List<Table3>()
};
var p4S = p4.ToList();
foreach (var p4FromGroup in p4S)
{
table2.Table3s.Add(new Table3
{
T3 = p4FromGroup.T3,
T4 = p4FromGroup.T4
});
}
t1.Table2s.Add(table2);
}
tables.Add(t1);
}
答案 1 :(得分:0)
我不确定我是否完全理解你的模型,但我认为一种方法可以类似于
List<Table1> itemsTable 1 =
items.select(i => new Table1() {
p1 = i.p1,
p2 = i.p2,
p3 = i.p3,
Table2 = i.p4.select(p4 => MapToTable2(p4)).ToList()
}).ToList();
private Table2 MapToTable2(P4 p4Items){
return new Table2() {
t1 = p4.T1,
t2 = p4.T2
Table3 = new Table3() {
t3 = p4.T3,
t4 = p4.T4
}
};
}