LINQ to Nhibernate用户定义的函数在where子句中 [英] LINQ to Nhibernate user defined function in where clause

查看:85
本文介绍了LINQ to Nhibernate用户定义的函数在where子句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作:

I'm trying to do the following:

var query =
    (from a in session.Query<A>()
    where a.BasicSearch(searchString) == true
    select a);

但是它一直给我这个异常"System.NotSupportedException"!

But it keeps giving me this exception "System.NotSupportedException"!

有什么办法解决这个问题吗?

Any idea how to solve this?

推荐答案

在LINQ查询中不能使用用户定义的函数. NHibernate linq提供程序不知道"如何将您的函数转换为SQL.

It is not possible to use user-defined functions in a LINQ query. The NHibernate linq provider does not 'know' how to translate your function into SQL.

LINQ to NHibernate的工作方式是检查运行时提供的LINQ表达式,并将其在此表达式树中找到的内容转换为常规SQL表达式.这是一篇很好的文章,可以使您对表达式树有一些了解:

LINQ to NHibernate works by inspecting the LINQ expression that you provide at runtime, and translating what it finds in this expression tree into a regular SQL expression. Here's a good article to get some background on expression trees: http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx

但是,您可以使用此处讨论的技术,以另一种方式重用谓词. . (但是我不确定这是否可以与NHibernate一起使用.)如果可以使用,它将看起来像这样:

You CAN reuse predicates like this in another way however, using the techniques discussed here. (I'm not sure if this works with NHibernate however.) IF it works it would look something like this:

// this could be a static method on class A
public static Expression<Func<A, bool>> BasicSearch(string criteria)
{
    // this is just an example, of course
    // NHibernate Linq will translate this to something like 
    // 'WHERE a.MyProperty LIKE '%@criteria%'
    return a => criteria.Contains(a.MyProperty); 
}

用法:

from a in Session.Query<A>().Where(A.BasicSearch(criteria))

更新:显然NHibernate会有问题.请参阅此博客文章,了解应该使用的版本.

UPDATE: apparently there will be issues with NHibernate. See this blog post for a version that ought to work.

这篇关于LINQ to Nhibernate用户定义的函数在where子句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆