【发布时间】:2016-05-15 10:24:44
【问题描述】:
我有一个 SqlServer 函数,该函数根据输入执行 cte 递归选择,输入是一个带有 ids 的 csv 字符串。
不幸的是,我不能在我的函数中使用“option(maxrecursion 0)”,它必须在函数执行时使用。问题是我找不到如何将此选项与 EntityFramework 的 EntitySql 一起使用。
考虑到我的函数叫做MyRecursiveFunction,这里有一些代码sn-ps:
public virtual IQueryable<MyFunctionReturnType> ExecuteMyFunction(IObjectContextAdapter objContextAdapter, string csvIds)
{
var idsParam = new ObjectParameter("idsParam", csvIds);
// This is the original one, that works, but has no "option(maxrecursion 0)"
return objContextAdapter.CreateQuery<MyFunctionReturnType>("[MyRecursiveFunction](@idsParam)", idsParam);
// gives me an error of incorrect syntax near "option"
return objContextAdapter.CreateQuery<MyFunctionReturnType>("select VALUE tblAlias from [MyRecursiveFunction](@idsParam) as tblAlias OPTION(MAXRECURSION 0)", idsParam);
// Also gives me syntax error:
return objContextAdapter.CreateQuery<MyFunctionReturnType>("MyRecursiveFunction(@idsParam) option(maxrecursion 0)", idsParam);
}
有人知道如何将option(maxrecursion 0) 与 entitySql 一起使用吗?
我知道我可以使用“ExecuteStoreQuery”来执行我想要的任何 sql 查询,但我确实需要一个 IQueryable,因为“ExecuteMyFunction”的返回将在实现之前与另一个 IQueryable 结合。
请节省您的时间,不要建议同时调用ExecuteStoreQuery 和AsQueryable.... 我真的不想实现整个结果集,因为我只会实现 10 个分页结果。
这是我的 TVF 的表示:
-- Consider that I have the given table for executing this function.
-- This table has a foreign key to itself, as the data represents a tree, like an organization chart
CREATE TABLE MyTable
(
Id INT,
ParentId INT, -- FK to 'MyTable'.'Id',
Name VARCHAR(400)
)
-- Here is my function definition:
CREATE FUNCTION MyRecursiveFunction (@idsParam VARCHAR(MAX))
RETURNS TABLE
AS
RETURN
(
-- create a cte for recursively getting the data
with myCte (id, parentId) as
(
SELECT tbl.Id, tbl.ParentId FROM MyTable AS tbl
-- This function just transform the varchar into a table of "Value"
INNER JOIN [dbo].[SplitTextIntoTableOfInt](@idsParam, ',') AS ids ON a.ParentId = ids.Value
UNION ALL
SELECT a.Id, a.ParentId FROM myCte AS parent
INNER JOIN MyTable tbl ON tbl.ParentId = parent.Id
)
SELECT * FROM myCte -- I can't use 'option(maxrecursion 0)' in here
)
【问题讨论】:
-
直到您使用 foreach 迭代
IQueryable或IEnumerable、ToList()、FirstOrDefault()... 不会向数据库发送查询。您是否真的尝试过ExecuteStoreQuery后跟AsQueryable()?我对此并不完全确定,因为我很少使用 EF 进行 sql 查询,但可能只有一个查询会访问数据库。正如我所说,我对此并不完全确定,如果我错了,请原谅:) -
我测试过了。 ExecuteStoreQuery 返回的 IEnumerable 在我使用它之前不会被执行,但由于它是一个 IEnumerable,而不是一个 IQueryable(它调用“AsQueryable”并没有什么不同),它已经在内存中的对象中转换,所以当我尝试将它与另一个 IQueryable 结合并实现它,这是我的场景,抛出异常。
标签: c# sql-server entity-framework common-table-expression entity-sql