我使用Entity Framework Core 2.0.3获得以下代码:
IQueryable<Book> books = _context.Books.AsQueryable();
List<String> keywords = new List<String> { "travel" };
books = books.Where(x => keywords.Any(y => x.Title.Contains(y)));
var isNull = books == null; // isNull is false so books is not null
var booksCount = books.Count(); // Get exception
我检查过,书籍不是空的,但是当booksCount运行时,我得到:
System.NullReferenceException: Object reference not set to an instance of an object.
at lambda_method(Closure , String )
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
at System.Linq.Enumerable.WhereEnumerableIterator`1.GetCount(Boolean onlyIfCheap)
at lambda_method(Closure , QueryContext )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_1`1.<CompileQueryCore>b__0(QueryContext qc)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
知道为什么吗?
答案 0 :(得分:0)
对于Where
或Any
过滤器,lambda方法内部会抛出异常。考虑到您设置了keywords
,我在某处猜测x.Title
是null
。
由于LINQ查询的延迟执行,您之前没有看到错误(在您尝试枚举结果之前,不会执行过滤器。)