安装.Net 4.5
后,EF生成的查询出现问题。 linq中.Net 4.0
的相同查询正常工作。我正在使用Firebird数据库,它不支持命令OUTER APPLY
。有没有办法修改以下查询linq,以便它在.Net 4.5
?
当前的linq查询:
int[] AROIds = (from x in context.RISK_T_ASSESS_HIST
where (x.ID_RISKOBJECT.HasValue && x.F_CREATEDON >= Freq.StartDate
&& x.F_CREATEDON <= Freq.EndDate)
group x by x.ID_RISKOBJECT into gr
let lastCreated = gr.Max(p => p.F_CREATEDON)
select new
{
ObjId = gr.Key
, LastStatus = gr.Where(p => p.F_CREATEDON == lastCreated
&& p.ID_RISKOBJECT == gr.Key)
.Select(p => p.F_STATUS).FirstOrDefault()
}).Where(x => x.LastStatus == 0 || x.LastStatus == 1)
.Select(x => x.ObjId.Value).ToArray();
生成的SQL。净4.5:
SELECT
"Project1"."ID_RISKOBJECT" AS "ID_RISKOBJECT"
FROM (SELECT
"GroupBy1"."A1" AS "C1",
"GroupBy1"."K1" AS "ID_RISKOBJECT"
FROM ( SELECT
"Extent1"."ID_RISKOBJECT" AS "K1",
MAX("Extent1"."F_CREATEDON") AS "A1"
FROM "RISK_T_ASSESS_HIST" AS "Extent1"
WHERE (("Extent1"."ID_RISKOBJECT" IS NOT NULL)
AND ("Extent1"."F_CREATEDON" >= 2013-04-17))
AND ("Extent1"."F_CREATEDON" <= 2013-04-17)
GROUP BY "Extent1"."ID_RISKOBJECT"
) AS "GroupBy1" ) AS "Project1"
OUTER APPLY (SELECT FIRST (1)
"Extent2"."F_STATUS" AS "F_STATUS"
FROM "RISK_T_ASSESS_HIST" AS "Extent2"
WHERE (((("Extent2"."ID_RISKOBJECT" IS NOT NULL)
AND ("Extent2"."F_CREATEDON" >= 2013-04-17))
AND ("Extent2"."F_CREATEDON" <= @2013-04-17))
AND (("Project1"."ID_RISKOBJECT" = "Extent2"."ID_RISKOBJECT") OR (("Project1"."ID_RISKOBJECT" IS NULL)
AND ("Extent2"."ID_RISKOBJECT" IS NULL)))) AND (("Extent2"."F_CREATEDON" = "Project1"."C1")
AND ("Extent2"."ID_RISKOBJECT" = "Project1"."ID_RISKOBJECT")) ) AS "Limit1"
WHERE (0 = "Limit1"."F_STATUS") OR (1 = "Limit1"."F_STATUS")
答案 0 :(得分:1)
确定。唯一的解决方案,就是我在初始表中读到列表时发现的。不幸的是,不是我的意思,但它确实有效。
AIds = (from x in
(
context.RISK_T_ASSESS_HIST.Where(x => x.ID_RISKOBJECT.HasValue && x.F_CREATEDON >= Freq.StartDate && x.F_CREATEDON <= Freq.EndDate)
.Select(x => new { x.ID_RISKOBJECT, x.F_CREATEDON, x.F_STATUS }).ToList()
)
group x by x.ID_RISKOBJECT into gr
let lastCreated = gr.Max(p => p.F_CREATEDON)
select new
{
ObjId = gr.Key
,
LastStatus = gr.Where(p => p.F_CREATEDON == lastCreated && p.ID_RISKOBJECT == gr.Key).Select(p => p.F_STATUS).FirstOrDefault()
}).Where(x => x.LastStatus == 0 || x.LastStatus == 1).Select(x => x.ObjId.Value).ToArray();
此问题实体框架将在其论坛上作为错误传递。