[英]How to select top result for a given ID then join that into another table EF Core LINQ
For the life of me I am unable to google my way out of this one.对于我的生活,我无法通过谷歌搜索我的出路。
I have 2 tables within a database 1. Computers 2. UserLogins我在数据库中有 2 个表 1. 计算机 2. UserLogins
Essentially, I'm trying to get the latest login entry from the "UserLogins" table, and join it with the corresponding entry in the "Computers" table.本质上,我试图从“UserLogins”表中获取最新的登录条目,并将其与“Computers”表中的相应条目连接起来。
This sounds simple enough, but I haven't sat through enough LINQ/EF Core courses yet to figure out how to do this correctly it seems.这听起来很简单,但我还没有参加足够多的 LINQ/EF Core 课程,似乎还没有弄清楚如何正确地做到这一点。
Here is some SQL that I know functions how I expect it to:这是一些 SQL,我知道我期望它的功能:
SELECT * FROM ComputerInfo
LEFT JOIN (
SELECT LoginID, UserID, l.ComputerName, IpAddress, l.LoginTime FROM UserLogins as l
INNER JOIN (
SELECT ComputerName, MAX(LoginTime) as LoginTime
FROM UserLogins
GROUP BY ComputerName) as max on max.ComputerName = l.ComputerName and max.LoginTime = l.LoginTime
) as toplogin on toplogin.ComputerName = ComputerInfo.ComputerName
For reference, I am going to be implementing this in my Controller.cs class, and I am using: EF Core (3.1.2) ASP.NET Core (3.1)作为参考,我将在我的 Controller.cs class 中实现这个,我正在使用:EF Core (3.1.2) ASP.NET Core (3.1)
I do have a couple queries I was experimenting with that return the results, but I can't join them without errors:我确实有几个我正在尝试返回结果的查询,但我不能毫无错误地加入它们:
var computerQuery = _context.ComputerInfo
.OrderBy(on => on.ComputerName)
var userQuery = _context.UserLogins
.Select(p => p.ComputerName)
.Distinct()
.Select(id => _context.UserLogins
.OrderByDescending(p => p.LoginTime)
.FirstOrDefault(p => p.ComputerName == id))
.ToListAsync();
So I kind of found a shotty way to get this done I think.所以我觉得我找到了一种很有效的方法来完成这件事。 Not sure if it is correct but here is what I came up with:不确定它是否正确,但这是我想出的:
I Created a new class called "ComputerInfoFull" which basically was just "ComputerInfo" && "UserLogins" combined, and used this for the linq query:我创建了一个名为“ComputerInfoFull”的新 class,它基本上只是“ComputerInfo”&&“UserLogins”的组合,并将其用于 linq 查询:
var initial = from computerInfo in _context.ComputerInfo
from userInfo in _context.UserLogins
.Where(o => o.ComputerName == computerInfo.ComputerName)
.OrderByDescending(o => o.LoginTime).Take(1)
select new ComputerInfoFull(computerInfo, userInfo);
I'm very sure there is a cleaner Lambda way of writing this, but I can't figure out how to make it work right.我很确定有一种更清洁的 Lambda 方式来写这个,但我不知道如何让它正常工作。 Too much stuff going on for my tiny brain to handle lol.太多的事情让我的小脑袋处理不了哈哈。 If anyone has any ideas on how I can make this cleaner please let me know so I can learn.如果有人对如何制作这种清洁剂有任何想法,请告诉我,以便我学习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.