LINQKit + EF Core:Where 子句作为方法错误

LINQKit + EF Core: Where clause as method error

我正在使用 LINQKit.Core 1.1.17,我想在 Expression Func 中使用我的方法。我的问题是出现错误:

The LINQ expression 'DbSet .Where(v => TestService.Distance( x1: __current_X_0, y1: __current_Y_1, x2: v.X, y2: v.Y) < __8__locals1_maxDistance_2)' 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.

这是我的代码。

表达式:

Expression<Func<Test, bool>> exp = v => Distance(current.X, current.Y, v.X, v.Y) < maxDistance;

距离法:

    private double Distance(int x1, int y1, int x2, int y2)
    {
        var x = Math.Abs(x1 - x2);
        var y = Math.Abs(y1 - y2);

        return Math.Sqrt(x ^ 2 + y ^ 2);
    }

是否可以使用 LINQKit 来实现?有没有更好的方法以这种方式查询数据库?

您可以将此方法定义为 ExpandableAttribute

public static class HelperFunctions
{
    [Expandable(nameof(DistanceImpl))]
    public static double Distance(int x1, int y1, int x2, int y2)
    {
        var x = Math.Abs(x1 - x2);
        var y = Math.Abs(y1 - y2);

        return Math.Sqrt(x ^ 2 + y ^ 2);
    }

    private static Expression<Func<int, int, int, int, double>> DistanceImpl()
    {
        rerutn (x1, y1, x2, y2) =>
            Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }
}

那么你可以在过滤器中使用这个功能:

var query = query
   .AsExpandable()
   .Where(q => HelperFunctions.Distance(q.x1, q.y1, q.x2, q.y2) < maxDistance);

LINQKit 将注入 DistanceImpl 中定义的 lambda 主体,让 EF LINQ 翻译器满意。