【问题标题】:Multi Table join and group by in LinqLinq中的多表连接和分组
【发布时间】:2017-09-19 13:17:48
【问题描述】:

我有 4 张桌子,没有其他类似的 FK:

表 1:ID、编号、日期、价格

Table2:ID、编号、日期、价格、Table1Number、Table1Date

Table3:ID、编号、日期、价格、Table2Number、Table2Date

Table4:ID、编号、日期、价格、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 中加入他们并获得任何表的总价!

【问题讨论】:

  • 请展示一些模型以及您尝试过的内容。 SO 有一个很棒的文档部分,其中包含 linq 查询示例,包括连接
  • 表 2、3、4 小计中的 SUM 是来自之前的其他表还是分开的?

标签: c# sql asp.net linq


【解决方案1】:

这可能不是那么有用。您可以做的是使用 LinqPad 尝试查询。使用此代码,我可以获得 4 个表并获得不同表的总数。 Table1 和 Table2 的总和只是 1 条记录的价格。 Table3 的总和是属于 Table1 和 Table2 的所有记录的总和。 Table4 有 2 个总数,因为 Table3 与 2 个 Tables4 有关系。

如果您提供更多详细信息,也许我可以进一步帮助您。

    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;}
}

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 2013-01-29
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多