我有一个票务系统,我试图根据仍在打开的票证获取最后添加的票证的一些基本信息。
以下是汇总的表格,包括我不查询的其他列:
票务表
TicketId
CustomerId
DateIn
CallNature
OpenClosed
TicketDetails表
TicketDetailsId
TicketId
TicketNote
DateLogged
这是SQL查询:
SELECT
t.TicketId,
t.CustomerId,
t.DateIn,
(SELECT TOP 1 td.DateLogged
FROM TicketDetails td
WHERE td.TicketId = t.TicketId
ORDER BY td.DateLogged DESC) DateLogged
FROM
Tickets t
WHERE
t.OpenClosed = 1
这是我当前的Linq查询:
var result = from t in ef.Tickets
where t.OpenClosed == true
select new
{
TicketId = t.TicketId,
CustomerId = t.CustomerId,
DateIn = t.DateIn,
DateLogged = (from td in ef.TicketDetails
where td.TicketId == t.TicketId
orderby td.DateLogged descending
select td.DateLogged).Take(1)
};
以下是Linq查询的结果示例:
TicketId = 11000
CustomerId = 4622
DateIn = 2018-01-25T00:00:00
DateLogged = 0001-01-01T00:00:00
应为:
TicketId = 11000
CustomerId = 4622
DateIn = 2018-01-25T00:00:00
DateLogged = 2018-12-12T13:32:42
我没有示例中的所有字段,但是它们与问题无关。
运行SQL查询时,结果符合预期。当我运行Linq查询时,除了DateLogged之外,所有字段都被填充,它一直返回默认值(0001-01-01)。
我已经确认每个票证至少要有1个票证明细可以退回。
答案 0 :(得分:0)
归因于尼尔提到的延迟执行的最终解决方案是:
var result = (from t in ef.Tickets
where t.OpenClosed == true
select new {
TicketId = t.TicketId,
CustomerId = t.CustomerId,
DateIn = t.DateIn,
DateLogged = (from td in ef.TicketDetails
where td.TicketId == t.TicketId
orderby td.DateLogged descending
select td.DateLogged).Take(1).FirstOrDefault()
}).ToList();
以及指向解释Linq查询执行之间差异的帖子的链接。
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/query-execution