![](/img/trans.png)
[英]How to write a LINQ to Entities query with List in a “WHERE” condition
[英]How to write fast subquery in where condition in linq
我嘗試在linq條件條件下編寫子查詢。 但是,當我在sql server profiler中查看sql語法時,我的查詢看起來很復雜而且很長,並且在服務器中發生了超時錯誤。
我想編寫如下查詢。
SELECT
T1.Id,
T2.Id,
DATEADD(HOUR,
ISNULL(
(
SELECT
MAX(T3.MaxHour) AS [MaxHour]
FROM TABLE3 T3 WITH(NOLOCK)
WHERE
T1.CategoryId=T3.CategoryId
),
0),T1.EndDate
),
T1.StartDate
FROM
TABLE1 T1 WITH(NOLOCK)
LEFT OUTER JOIN TABLE2 T2 WITH(NOLOCK) ON T1.Id=T2.Id
WHERE
DATEADD(HOUR,
ISNULL(
(
SELECT
MAX(T3.MaxHour) AS [MaxHour]
FROM TABLE3 T3 WITH(NOLOCK)
WHERE
T1.CategoryId=T3.CategoryId
),
0),T1.EndDate
)
> '2014-11-05 00:00:00'
AND
T1.StartDate < '2014-11-05 06:00:00'
我這樣寫我的linq表達式。
var actualData = from T1 in _context.TABLE1
join T2 in _context.TABLE2 on T1.Id equals T2.Id into data
from x in data.DefaultIfEmpty()
where
EntityFunctions.AddHours(T1.EndDate,
(
(int?)((from T3 in _context.TABLE3
where
T3.CategoryId == T1.CategoryId
select
T3).Max(row => row.MaxHour))
) ?? 0
) >= '2014-11-05 00:00:00'
&& T1.StartDate < '2014-11-05 06:00:00'
select
new
{
Id1 = T1.Id,
Id2 = T2.Id,
StartDate = T1.StartDate,
EndDate = EntityFunctions.AddHours(T1.EndDate,
(
(int?)((from T3 in _context.TABLE3
where
T3.CategoryId == T1.CategoryId
select
T3).Max(row => row.MaxHour))
) ?? 0
)
};
但是,我似乎不想在sql中看到它。
我如何用linq書寫?
謝謝。
嘗試:
var actualData = from T1 in _context.TABLE1
join T2 in _context.TABLE2 on T1.Id equals T2.Id into data
from x in data.DefaultIfEmpty()
let endate = EntityFunctions.AddHours(T1.EndDate,
(
(
from T3 in _context.TABLE3
where T3.CategoryId == T1.CategoryId
select T3).Max(row => row.MaxHour)
)
) ?? 0
)
where
enddate >= '2014-11-05 00:00:00'
&& T1.StartDate < '2014-11-05 06:00:00'
select
new
{
Id1 = T1.Id,
Id2 = T2.Id,
StartDate = T1.StartDate,
EndDate = enddate
};
而且我懷疑您可以將強制類型轉換為(int?)
,因為默認情況下max(int)
返回int?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.