问题
I have one question to ask you, dear community, as you may have guessed. So. I want NHibernate to filter the results of a query basing on the evaluation of table-valued sql function. Possible SQL query generated by NHibernate may look similar to the following:
SELECT
[whatever]
FROM
[whatever]
INNER JOIN dbo.FnMyTableValuedFunction() as MyAlias ON
[whatever].FirstDesiredKey = MyAlias.FirstDesiredKey
AND
[whatever].SecondDesiredKey = MyAlias.SecondDesiredKey
Or it can be written this way:
SELECT
[whatever]
FROM
[whatever]
WHERE
EXISTS(
SELECT
1
FROM
dbo.FnMyTableValuedFunction() AS MyAlias
WHERE
[whatever].FirstDesiredKey = MyAlias.FirstDesiredKey
AND
[whatever].SecondDesiredKey = MyAlias.SecondDesiredKey
)
Such query I want to generate using Criteria API.
As far as I know, there is no way to tell NHibernate what it should join and how. So the one solution that may exist is the second one.
Unfortunately I wasn't lucky enough to find out how to use table-valued function as a query source for correlated subquery. Can you help me with that one?
回答1:
All NHibernate query methods except SQL (HQL, Criteria, Linq, QueryOver) work on entities, not tables or any other DB artifacts.
Therefore, if you are using Criteria, you need to either map FnMyTableValuedFunction
to an entity, or use SQLCriterion
for an arbitrary SQL block.
With the latter, yes, EXISTS
is probably the way to go. You can just enclose the whole condition (including the EXISTS) in a SQLCriterion.
回答2:
You might be able to add a custom method into a derived SQLDialect, and use that in a criteria, look into RegisterFunction
in NHibernate.Dialect.Dialect which all Dialects inherits.
来源:https://stackoverflow.com/questions/4249885/can-i-use-table-valued-function-as-query-source-in-nhibernate