较长的 LINQ 查询会破坏 SQLite 解析器 - 简化吗?
我正在使用 C# 和 LINQ 编程搜索 SQLite 数据库。 搜索的想法是,您可以提供一个或多个关键字,其中任何一个关键字都必须包含在多个列条目中的任何一个中,以便将该行添加到结果中。 该实现由多个 linq 查询组成,这些查询全部通过联合组合在一起。必须考虑的关键字和列越多,查询就越复杂。这可能会导致 SQL 代码,这对 SQLite 解析器来说太长了。
下面是一些示例代码来说明:
IQueryable<Reference> query = null;
if (searchAuthor)
foreach (string w in words)
{
string word = w;
var result = from r in _dbConnection.GetTable<Reference>()
where r.ReferenceAuthor.Any(a => a.Person.LastName.Contains(word) || a.Person.FirstName.Contains(word))
orderby r.Title
select r;
query = query == null ? result : query.Union(result);
}
if (searchTitle)
foreach (string word in words)
{
var result = from r in _dbConnection.GetTable<Reference>()
where r.Title.Contains(word)
orderby r.Title
select r;
query = query == null ? result : query.Union(result);
}
//...
有没有一种方法可以生成更紧凑的 SQL 来构造查询? 我尝试通过在每次循环后对查询调用 GetEnumerator() 来强制创建较小的 SQL 语句。但显然 Union() 不对数据进行操作,而是对底层 LINQ/SQL 语句进行操作,因此无论如何我都会生成长语句。
我现在能想到的唯一解决方案是在每个“子查询”之后真正收集数据并对实际数据而不是在语句中进行联合。有什么想法吗?
I'm programming a search for a SQLite-database using C# and LINQ.
The idea of the search is, that you can provide one or more keywords, any of which must be contained in any of several column-entries for that row to be added to the results.
The implementation consists of several linq-queries which are all put together by union. More keywords and columns that have to be considered result in a more complicated query that way. This can lead to SQL-code, which is to long for the SQLite-parser.
Here is some sample code to illustrate:
IQueryable<Reference> query = null;
if (searchAuthor)
foreach (string w in words)
{
string word = w;
var result = from r in _dbConnection.GetTable<Reference>()
where r.ReferenceAuthor.Any(a => a.Person.LastName.Contains(word) || a.Person.FirstName.Contains(word))
orderby r.Title
select r;
query = query == null ? result : query.Union(result);
}
if (searchTitle)
foreach (string word in words)
{
var result = from r in _dbConnection.GetTable<Reference>()
where r.Title.Contains(word)
orderby r.Title
select r;
query = query == null ? result : query.Union(result);
}
//...
Is there a way to structure the query in a way that results in more compact SQL?
I tried to force the creation of smaller SQL-statments by calling GetEnumerator() on the query after every loop. But apparently Union() doesn't operate on data, but on the underlying LINQ/SQL statement, so I was generating to long statements regardless.
The only solution I can think of right now, is to really gather the data after every "sub-query" and doing a union on the actual data and not in the statement. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于类似的事情,您可能需要使用 PredicateBuilder,如所选的回答这个问题。
For something like that, you might want to use a PredicateBuilder, as shown in the chosen answer to this question.