如何将此SQL重写为Linq查询?
纯SQL
SELECT *
FROM contracts
INNER JOIN
(SELECT contractid, max(date) date
FROM contractlogs GROUP BY contractId) b
ON contracts.id = b.contractId
尝试Linq
from c in _db.Contracts
join sub in (from cl in _db.ContractLogs
group cl by cl.contractId into g
select new { contractId = g.contractId, changedate = g.Max(x => x.date)})
on c.id equals sub.contractId
select new { c, cl }
查询的目标是选择所有最新更新的合约(首先)(在contractLogs中)。我目前对如何选择工作感到困惑。理想情况下,我试图返回一个对象与c &cl .
您可以通过按降序排序并取第一个来获取最近的日志:
from c in _db.Contracts
let mostRecentContractLog = c.ContractLogs
.OrderByDescending(cl => cl.date)
.FirstOrDefault()
select new { c, mostRecentContractLog }
如您所见,我假设您有一个导航属性Contract.ContractLogs
。始终强烈建议使用导航属性而不是手动编码的连接。
最字面的翻译将涉及您调用ContractLogs上的groupby,然后将其加入Contacts。我认为你的操作顺序在你的LINQ尝试是有点off,但我不经常使用查询语法,所以我不肯定。不管怎样,我想你会更喜欢这样的东西;
_db.ContractLogs.GroupBy(x => x.contractId).Select(x => new { contractid = x.Key, changedate = x.Max(y => y.date) })
这样你就可以连接到_db了。合同,但我认为你可以写它更简单的地方,虽然这可能是较少优化的LINQ到SQL提供程序。不管怎样,用一个连接来完成这个例子;
OldQuery.Join(_db.Contracts, cl => cl.contractid,
c => c.contractid, (cl, c) => cl);
在这种情况下,将查询和子查询分开编写通常更容易:
var subQuery =
from cl in _db.ContractLogs
group cl by cl.contractId into g
select new { contractId = g.Key, date = g.Max(cl => cl.date) };
var query =
from c in _db.Contracts
join cl in subQuery on c.contractId equals cl.contractId
select new { contract = c, cl.date };
你可以试试:
from c in _db.Contracts
select new
{
c,
cl = _db.ContractLogs.Where(l => l.contractId == c.contractId).OrderByDescending(l => l.date).FirstOrDefault()
}