首页 > 解决方案 > 连接多个表并返回表 2 中的最后一条记录

问题描述

我有几张桌子table1,table2和。所有这些表都有关系。 可能有一个或多个记录,但我只对最后插入的记录感兴趣。table3table4MyIDTable2

我编写了以下查询以获得所需的输出,但是,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(),但结果仍然相同。如何获取最新的table2使用记录join

标签: c#entity-frameworklinqentity-framework-coreef-core-2.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分配了两次。我也从 using 切换First()到,FirstOrDefault()因为这应该更安全和健壮(尽管我不确定 MySql 会有什么不同)。


推荐阅读