NullReferenceException in EF Core when using StringComparison overload for predicates

戏子无情 提交于 2021-02-05 11:46:53

问题


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.WhereEnumerableIterator1.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext() at System.Linq.Enumerable.First[TSource](IEnumerable1 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!