连接多个表并返回表2中的最后一条记录

时间:2018-11-28 18:26:19

标签: c# entity-framework linq entity-framework-core ef-core-2.1

我只有几个表table1table2table3table4。所有这些表都具有关系MyIDTable2可能有一个或多个记录,但是我只对最后插入的记录感兴趣。

我编写了以下查询以获取所需的输出,但是,table2仍返回多个记录。

var query = (from t1 in table1
            join t2 in table2
                on t1.MyID equals t2.MyID
                into t2Table
            join t3 in table3
                on t1.MyID equals t3.MyID 
                into t3Table
            join t4 in table4
                on t1.MyID equals t4.MyID 
                into t4Table
            where t1.MyID == 1
            select new MyViewModel()
            {
                A = t1.A,
                B = t1.B,
                C = t1.C,
                D = t2Table
                    .OrderByDescending(x => x.MyDate)
                    .Select(x => x.D).First(),
                E = t2Table
                    .OrderByDescending(x => x.MyDate)
                    .Select(x => x.E).First(),
                F = t2Table
                    .OrderByDescending(x => x.MyDate)
                    .Select(x => x.F).First(),
                G = t3Table.Select(c => new TModel()
                {
                    Col1 = c.Col1,
                    Col1 = c.Col2,
                }).ToList(),
                H = t4Table.Select(l => new PModel()
                {
                    Col1 = l.Col1,
                    Col2 = l.Languages.Col2,
                }).ToList(),
            });

对于D, E, F,我也尝试选择.Max(),但结果仍然相同。如何使用table2join获取最新记录?

1 个答案:

答案 0 :(得分:1)

不要使用显式联接。通过以下方式重写查询:

var query = table1
        .Where(t1 => t1.MyID == 1)
        .Select(t1 => new MyViewModel()
        {
            A = t1.A,
            B = t1.B,
            C = t1.C,
            D = table2.Where(t2 => t2.MyID == t1.MyID).OrderByDescending(x => x.MyDate).Select(x => x.D).FirstOrDefault(),
            E = table2.Where(t2 => t2.MyID == t1.MyID).OrderByDescending(x => x.MyDate).Select(x => x.E).FirstOrDefault(),
            F = table2.Where(t2 => t2.MyID == t1.MyID).OrderByDescending(x => x.MyDate).Select(x => x.F).FirstOrDefault(),
            G = table3.Where(t3 => t3.MyID == t1.MyID).Select(c => new TModel()
            {
                Col1 = c.Col1,
                Col2 = c.Col2,
            }).ToList(),
            H = table4.Where(t4 => t4.MyID == t1.MyID).Select(l => new PModel()
            {
                Col1 = l.Col1,
                Col2 = l.Languages.Col2,
            }).ToList(),
        });

目前,我们将忽略可能的性能优化。这应该具有您想要的结果。另请注意,我固定了G属性的分配(您在Col1分配了两次。我也从使用First()切换到FirstOrDefault(),因为这样做应该更安全,更可靠(尽管我不确定MySql会有什么不同)。