c# - 连接多个表并返回表 2 中的最后一条记录
问题描述
我有几张桌子table1
,table2
和。所有这些表都有关系。 可能有一个或多个记录,但我只对最后插入的记录感兴趣。table3
table4
MyID
Table2
我编写了以下查询以获得所需的输出,但是,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
?
解决方案
不要使用显式连接。用以下方式重写您的查询:
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 会有什么不同)。
推荐阅读
- php - 不同数组中键的值
- javascript - 来自 JSON 的 DOM 表
- webrtc - WebRTC replaceTrack,getStats不返回audioInputLevel
- javascript - document.getElementsByName("q1").disabled = true 不工作
- javascript - 即使单击标签区域,引导程序默认表单输入也会打开。我该如何防止这种情况?
- python - 如何在python中组合多个列
- javascript - 在自定义元素构造函数调用中维护 JS 范围
- join - 水晶报表外部加入
- c# - 如何在我的 DbContext 上切换连接?
- c# - 通过网络摄像头识别人并获取旧历史数据