简体   繁体   English

在SQL中推迟执行where

[英]deferred execution of where in sql

i have an editor where people can create custom sql-queries. 我有一个编辑器,人们可以在其中创建自定义sql查询。 those queries are NHibernate.IQuery objects. 这些查询是NHibernate.IQuery对象。

in our project we are using NHibernate.Linq.LinqExtensionMethods.Query to get an IQueryable object which can be used to apply filters that are executed deferred (everything on the DB). 在我们的项目中,我们使用NHibernate.Linq.LinqExtensionMethods.Query来获取IQueryable对象,该对象可用于应用延迟执行的过滤器(DB上的所有内容)。

now i want to create another filter that is based on the custom sql-queries. 现在,我想创建另一个基于自定义sql查询的过滤器。 what i want is something like this: 我想要的是这样的:

queryable.Where(x=> <sql-query contains x>)

the only thing i can do right now is execute the sql-query beforehand and then filter the queryable with the resulting list of elements. 我现在唯一能做的就是事先执行sql-query,然后使用结果元素列表过滤可查询对象。

IList<T> elements = query.List<T>();
queryable.Where(x => elements.Contains(x)).ToList();

the problem with that approach is, that the list of elements can be huge. 这种方法的问题在于,元素列表可能很大。 if its possible, i would like to perform the whole statement directly on the database, so that i dont have to transfer all objects to my application, then send all objects back to the database as the filter-parameters... 如果可能的话,我想直接在数据库上执行整个语句,这样我就不必将所有对象都传输到我的应用程序,然后将所有对象作为过滤器参数发送回数据库...

edit: the first query (the one yielding the list of elements to check for in the second query) is constructed from a plain sql-string as follows: 编辑:第一个查询(产生第二个查询中要检查的元素列表的查询)是由普通的sql-string构造的,如下所示:

ISQLQuery sqlQuery = CurrentSession.CreateSQLQuery(myQueryString);//create query
sqlQuery.AddEntity(typeof (T)); //set result type
IQuery query = sqlQuery.SetReadOnly(true);

If you have id's, then you should select them in your query , and compare it to the corresponding id column in the second query. 如果您有ID,则应在query选择ID,然后将其与第二个查询中的相应ID列进行比较。

var elementIdsToUseInContain = query
    .Select(x => x.YourIdProperty);
var result = queryable
    .Where(x => elementIdsToUseInContain.Contains(x.YourIdPropertyToCompareTo))
    .ToList();

Note: I haven't tested it, but it is fairly standard Linq. 注意:我尚未测试过,但这是相当标准的Linq。 It depends on if NHibernate supports it, which i do not know. 这取决于NHibernate是否支持它,我不知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM