问题
We are converting a project from using EF to using EF Core. We have the following line of code which used to work but now does not:
// throws NullReferenceException
var u = db.Users.FirstOrDefault(x => x.PresenterID.Equals(uid, StringComparison.OrdinalIgnoreCase));
However, if we don't use the StringComparison
overload, it works:
// this works
var u = db.Users.FirstOrDefault(x => x.PresenterID.Equals(uid));
This is a large project and we would like to avoid finding and modifying all code that does such comparisons. Why does this throw a NullReferencException and can it be avoided without changing our code? Here is the stack trace. Thanks.
at lambda_method(Closure , User ) at System.Linq.Enumerable.WhereEnumerableIterator
1.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable
1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__17
2.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext() at System.Linq.Enumerable.First[TSource](IEnumerable
1 source) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.b__0(QueryContext qc) at Our.Project.Service.ContractsFolderService.ValidateContractUsers(BIContract xmlContract, IDataContext db) in C:\Projects\Out.Project\Main\Service\ContractsFolderService.cs:line 436
回答1:
According to this open issue on the EntityFrameworkCore Github repo, that overload is not yet supported with LINQ to SQL. See this specific comment which gives some detail on the problem preventing this overload from being translated: https://github.com/aspnet/EntityFrameworkCore/issues/1222#issuecomment-443116169
I'm guessing that the null reference exception is occurring because its pulling back all the results to evaluate your string comparison on the client side, and for one or more of those results PresenterID
is null.
来源:https://stackoverflow.com/questions/55498473/nullreferenceexception-in-ef-core-when-using-stringcomparison-overload-for-predi