EFCore 3.1 - Exists query via Any; Query cannot be translated

丶灬走出姿态 提交于 2021-01-27 11:20:07

问题


We're using EFCore 3.1 and trying to build a query using Exists by means of .Any() which spans 2 properties.

var selectionCriteria = someHugeList.Select(sh => new { sh.Id, sh.StatusCode }).ToList()
var resultsQry = _myContext.SomeClass
                           .Include(sc => sc.DetailRecords)
                           .Where(sc => selectionCriteria.Any(crit => crit.Id == sc.Id 
                                                                   && crit.StatusCode == sc.StatusCode));

var results = await resultsQry.ToListAsync()

When running this query (even with a small amount (5 items) of selection criteria items it provides the following error message;

System.InvalidOperationException: LINQ expression 'DbSet .Where(c => __selectionCriteria_0 .Any(crit => crit.Id == sc.Id && crit.StatusCode == sc.StatusCode))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

Seems the problem resides in the fact that there are 2 properties included in the .Any clause. A where exists in sql normally can do this without problem. EFCore seems to find this difficult.

Does anyone have an idea on how to solve this?


回答1:


just found this; https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#linq-queries-are-no-longer-evaluated-on-the-client

long story short; client evaluation is no longer working in EFCore 3.1 meaning this type of query (comparing a clientside list to a serverside list) doesn't work. You need to bring it to the client. My collegue pointed out to me just now that I didn't appreciate the error message to it's full potential :).

Changed my query as follows (not optimal, but no other solution yet):

var selectionCriteria = someHugeList.Select(sh => new { sh.Id, sh.StatusCode }).ToList()
var resultsQry = _myContext.SomeClass
                           .Include(sc => sc.DetailRecords)
                           .AsEnumerable() // this is the important part, pulling all the records client side so we can execute the .Any on the client.
                           .Where(sc => selectionCriteria.Any(crit => crit.Id == sc.Id 
                                                                   && crit.StatusCode == sc.StatusCode));

var results = await resultsQry.ToList() // no more async, because clientside


来源:https://stackoverflow.com/questions/60092959/efcore-3-1-exists-query-via-any-query-cannot-be-translated

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