我试图在用户输入字符串的地方进行搜索,然后在我的数据库中找到匹配的字符串。
目前,使用.Contains()
进行搜索工作正常。例如。
User Input: Park
Results: Central Park, Washing Square Park, Riverside Park, Park Avenue, Park Chester
但是,如果我使用.StartsWith()
而不是.Contains()
,则会导致抛出空引用异常。
var dbCode = await repo.GetAsync<List<DBCode>>(_ => _.Code.Equals(id) && _.Name.ToUpper().StartsWith(searchWord.ToUpper())); //Doesn't work, throws NRE
var dbCode = await repo.GetAsync<List<DBCode>>(_ => _.Code.Equals(id) && _.Name.ToUpper().Contains(searchWord.ToUpper())); //works fine
我想使用.StartsWith()
,所以我的预期结果如下:
User Input: Park
Result: Park Avenue, Park Chester
而不是所有在公园结束的单词。
我如何使用上面使用的方法做到这一点?
以下例外情况:
System.NullReferenceException: Object reference not set to an instance of an object.
at SQLite.TableQuery`1.CompileExpr(Expression expr, List`1 queryArgs)
at SQLite.TableQuery`1.CompileExpr(Expression expr, List`1 queryArgs)
at SQLite.TableQuery`1.GenerateCommand(String selectionList)
at SQLite.TableQuery`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at SQLite.AsyncTableQuery`1.<ToListAsync>b__9_0()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at DSNY.Novas.Data.SQLiteRepository`1.<GetAsync>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
此外,我在第一条评论中也使用了Generic Repository:Generic Repository for SQLite-Net in Xamarin Project
特别是:
public async Task<List<T>> GetAsync<TValue>(Expression<Func<T, bool>> predicate = null,
Expression<Func<T, TValue>> orderBy = null)
{
var query = Context.Table<T>();
if (predicate != null)
query = query.Where(predicate);
if (orderBy != null)
query = query.OrderBy<TValue>(orderBy);
return await query.ToListAsync();
}