我有一个Logins
表,它记录用户何时login
、logout
或loginFailed
及其时间戳。现在我想在上次 login
之后获取 loginFailed
的列表,并且 loginFailed
发生在 24 小时内。
我现在做的是先获取上次登录时间戳。然后使用第二个查询来获取最终列表。您认为我应该将这两个查询结合在一起吗?为什么不?为什么是?如果是怎么办?
var lastLoginTime = (from inRecord in db.Logins
where inRecord.Users.UserId == userId
&& inRecord.Action == "I"
orderby inRecord.Timestamp descending
select inRecord.Timestamp).Take(1);
if (lastLoginTime.Count() == 1)
{
DateTime lastInTime = (DateTime)lastLoginTime.First();
DateTime since = DateTime.Now.AddHours(-24);
String actionStr = "F";
var records = from record in db.Logins
where record.Users.UserId == userId
&& record.Timestamp >= since
&& record.Action == actionStr
&& record.Timestamp > lastInTime
orderby record.Timestamp
select record;
}
最佳答案
从长远来看,我认为这并不重要。无论您实际上如何在 LINQ to SQL 中构建查询,数据库服务器上的最终事件顺序都是
- 获取上次时间
- 使用 lastInTime 作为记录过滤器的一部分
现在...将其作为单个查询的一部分进行将节省实际日期时间的往返次数,因此您可以通过这种方式获得一些性能。但我建议您仅在绝对需要时才尝试合并它们,因为您的性能分析表明查询是一个瓶颈。
关于c# - Linq,我应该将这两个查询连接在一起吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2813637/