如何使用 LINQ 在 NHibernate 3 中实现关键字搜索?
我有一个看起来像这样的实体:
public class Media
{
public virtual string Caption { get; set; }
public virtual string Description { get; set; }
public virtual string Notes { get; set; }
}
我想做的是为用户提供在 Caption
、Description
和 Caption
上搜索多个关键字的能力代码>注释属性。换句话说,如果用户搜索“applebanana”,则应该搜索三个字符串属性以查看其中是否有任何包含“apple”和“ >香蕉'。
我尝试使用以下 LINQ 语句作为测试:
var query = new[] { "apple", "banana" };
// GetAll<T> returns an IQueryable<T>
repo.GetAll<Media>().Where(x => query.All(x.Caption.Contains));
但出现异常:
ArgumentException:“System.Linq.Expressions.UnaryExpression 类型的对象”无法转换为“System.Linq.Expressions.LambdaExpression”类型。
我知道 NHib 3.0 的 LINQ 提供程序并未实现 LINQ 的所有功能。我如何重写这个 LINQ 查询,使其与 NHibernate LINQ 兼容?
I have an entity that looks like this:
public class Media
{
public virtual string Caption { get; set; }
public virtual string Description { get; set; }
public virtual string Notes { get; set; }
}
What I'd like to do is provide the user with the ability to search on multiple keywords on the Caption
, Description
, and Notes
properties. In other words, if the user searches for 'apple banana', it should search through the three string properties to see if any of them contains 'apple' and 'banana'.
I tried the following LINQ statement as a test:
var query = new[] { "apple", "banana" };
// GetAll<T> returns an IQueryable<T>
repo.GetAll<Media>().Where(x => query.All(x.Caption.Contains));
But I'm getting an exception:
ArgumentException: 'Object of type System.Linq.Expressions.UnaryExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.
I know that the LINQ provider for NHib 3.0 does not implement all of LINQ's features. How would I rewrite this LINQ query so that it's NHibernate LINQ-compatible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住,即使您弄清楚如何使用 Linq 最佳地执行您想要的操作,它本质上仍然会被转换为 SQL 语句,根据定义,该语句将如下所示:
(Caption LIKE '%apple%' AND Caption LIKE '%banana'%) OR (Description LIKE '%apple%' AND Description LIKE '%banana%')..etc
或者当然,次优方法可能会导致返回每条记录,然后评估条件本地。
我的建议是研究 NHibernate.Search,它使用 Lucene 索引引擎作为后端。我认为这会更符合您想要做的事情。
Keep in mind, even if you figure out how to do do what you want with Linq optimally, it's still essentially going to be translated into a SQL statement that by defintion is going to look like the following:
(Caption LIKE '%apple%' AND Caption LIKE '%banana'%) OR (Description LIKE '%apple%' AND Description LIKE '%banana%')..etc
Or of course, the sub-optimal method might result in returning every record and then evaluating the conditions locally.
My suggestion is to look into NHibernate.Search, which uses the Lucene indexing engine as a back end. I think it will be more in tune with what you are looking to do.