2017-04-22 68 views
0

我有4个表,而不用任何FK别人是这样的:多表连接和组通过LINQ的

表1:身份证,号码,日期,价格

表2:身份证,号码,日期,价格,Table1Number,Table1Date

表3:身份证,号码,日期,价格,Table2Number,Table2Date

表4:身份证,号码,日期,价格,Table3Number,Table3Date

我想这样的输出:

Table1.Number,Table1.Date,Table1.Price,

Table2.Number,Table2.Date,Table2.Price(总价格)

Table3.Number,Table3.Date,Table3.Price(总价格)

Table4.Number,Table4.Date,Table4.Price(总价格)

table1-table2是One-One关系,但table2-table3和table3-table4是One-Many。

我困惑地加入他们在Linq并得到任何表的总价!

+1

请表现出一定的模型和你已经尝试了什么。 SO有一个很好的文档部分,其中包含连接的linq查询示例 –

+0

表2,3,4中的SUM是否与其他表中的SUM相同或是否是单独的? –

回答

0

这可能不是那么有用。你可以做的是用LinqPad试一下查询。通过这段代码,我能够得到4个表格并获得不同表格的总数。 Table1和Table2的总和只是1条记录的价格。 Table3的总和是属于Table1和Table2的所有记录的总和。 Table4有2个总和,因为Table3与2个表4有关系。

如果您提供更多的细节,也许我可以帮助你。

void Main() 
    { 

    var tables4a = new List<Table4>(){new Table4{id=1, price=40}, new Table4{id=2, price=41}}; 
    var tables4b = new List<Table4>(){new Table4{id=1, price=50}, new Table4{id=2, price=51}}; 
    var tables3 = new List<Table3>(){new Table3{id=1, price=20, tables4= tables4a}, new Table3{id=2, price=21, tables4 = tables4b}}; 
    var tables2 = new List<Table2>() {new Table2(){id=1, price=5, tables3= tables3, table1= new Table1(){ 
    id = 1, price = 11 
    }}}; 


    var Total123 = tables2.Where(x=>x.id ==1) 
    .SelectMany(x=>x.tables3, (table2,b)=>new{ 
    table2 
    }) 
    .SelectMany(x=>x.table2.tables3, (table_2,table_3)=>new{ 
    table_2, 
    table_3 
    }) 
    .Select(v=> new { 
    SumTable1= v.table_2.table2.table1.price, 
    SumTable2= v.table_2.table2.price, 
    SumTable3 =v.table_2.table2.tables3.Sum(x=>x.price), 
    SumTable4= v.table_3.tables4.Sum(x=>x.price), 
     }) 
     .Distinct() 
    ; 

    Total123.Dump(); 
} 


public class Table1 
{ 
    public int id {get;set;} 
    public int price {get; set;} 
} 

public class Table2 
{ 
    public int id {get;set;} 
    public int price {get; set;} 
    public Table1 table1 {get; set;} 
    public List<Table3> tables3 {get; set;} 
} 

public class Table3 
{ 
    public int id {get;set;} 
    public int price {get; set;} 
    public List<Table4> tables4 {get; set;} 
} 

public class Table4 
{ 
    public int id {get;set;} 
    public int price {get; set;} 
} 

enter image description here