我正在使用Entity Framework 5连接到SQL Server 2008.我已经将存储过程导入到我的项目中而没有任何问题。存储过程在过去执行完毕没有任何问题,直到我在LINQ中使用.GroupBy().First()
切换到获得不同的结果,通过在存储过程中使用OUTER APPLY
来获得唯一的结果。
我转而使用LINQ中OUTER APPLY
的SQL Server上的.GroupBy()
,因为当然SQL速度要快得多。
这是我的SQL:
@USERID VARCHAR(MAX) = NULL,
@ITEMTYPE VARCHAR(MAX) = NULL,
@ITEMSUBTYPE VARCHAR(MAX) = NULL,
@ITEMGROUP VARCHAR(MAX) = NULL,
@ITEMNO VARCHAR(MAX) = NULL
SELECT distinct orderformdump.itemno,
case when @userid = '' then NULL else CAST((SELECT top 1 [UNITPRICE] FROM [ICPRICP] WHERE [ITEMNO] = ICITEM.ITEMNO AND [PRICELIST] in (select priclist from ARCUS where IDCUST in (select CUSTID from WEBLOGINACCESS where [USER] = @USERID)) and [CURRENCY] = 'CDN' and DPRICETYPE = 1) AS DECIMAL(18,2)) end as price,
isnull(deals.isindeal, CAST(0 AS BIT) ) isindeal
FROM ORDERFORMDUMP
INNER JOIN ICITEM ON ICITEM.FMTITEMNO = orderformdump.itemno
outer apply
(
select top 1 CAST(1 AS BIT) as isindeal
from PRD2 INNER JOIN PRH on PRD2.CODE = PRH.CODE
where ICITEM.ITEMNO = PRD2.ITEMNO and PRH.ACTIVE = 1
and cast(GETDATE() as DATE) between PRH.STARTDATE and isnull(PRH.ENDDATE, cast(GETDATE() as DATE))
) deals
where
(@ITEMNO IS NULL or ICITEM.FMTITEMNO = @ITEMNO)
and
(@ITEMSUBTYPE is null or ORDERFORMITEMSUBTYPEDUMP.ITEMSUBTYPE = @ITEMSUBTYPE)
and
(@ITEMTYPE is null or ORDERFORMITEMTYPEDUMP.ITEMTYPE = @ITEMTYPE)
and
(@ITEMGROUP is null or ORDERFORMITEMGROUPDUMP.ITEMGROUP = @ITEMGROUP)
之前,OUTER APPLY
代替LEFT JOIN
我有两个isindeal
,而CASE
列位于...
case when PRH.ACTIVE = 1 and PRH.STARTDATE < cast(GETDATE() as DATE) and (PRH.ENDDATE IS NULL OR PRH.ENDDATE >= cast(GETDATE() as DATE)) then CAST(1 AS BIT) ELSE CAST(0 AS BIT) END as isindeal
...
LEFT JOIN PRD2 on ICITEM.ITEMNO = PRD2.ITEMNO
LEFT JOIN PRH on PRD2.CODE = PRH.CODE
...
声明中:
public partial class PRODUCTS_Result
{
public string itemno { get; set; }
public Nullable<decimal> price { get; set; }
public bool isindeal { get; set; }
}
这是Entity Framework中的导入类:
db.PRODUCTS(userid, itemtype, itemsubtype, itemgroup, itemno)
这是调用存储过程的方式:
db.PRODUCTS(userid, itemtype, itemsubtype, itemgroup, itemno).GroupBy(i => i.itemno).Select(x => x.First());
之前的调用方式如下:
db.PRODUCTS(null, null, null, null, null)
奇怪的是,只有在使用所有空参数调用存储过程时才会发生超时(例如((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
)
我尝试将超时设置为5分钟而不是默认的30秒{{1}},但它只运行了整整5分钟,但仍然超时。
存储过程在3-5秒内完成SQL Server中的执行,其中包含参数的所有NULL值,我检查了所有数据类型并且它们匹配,所以我不知道为什么我只得到此超时错误有时。
答案 0 :(得分:1)
简答:将OPTION(RECOMPILE)添加到此查询
答案很长:阅读Erland Sommarskog的Dynamic Search Conditions in TSQL