EF Core - 在 Where 中使用扩展方法

我有以下扩展方法来计算产品的平均评分。


public static class Extensions

{

    public static decimal CalculateAverageRating(this ICollection<ProductReview> productReviews)

    {

        // Calculate and return average rating


        return averageRatings;

    }

}

我想在 EF 可查询中使用此方法,如下所示:


var products = _context.Products

            .Include(pr => pr.ProductReviews)

            .AsQueryable();


        if(searchParams.Rating != 0)

            products = products.Where(p => p.ProductReviews.CalculateAverageRating() == searchParams.Rating);

但是,我不断遇到错误“ArgumentException:方法的类型为'System.Collections.Generic.IAsyncEnumerable 1[Products.Reviews.ProductReview]' cannot be used for parameter of type 'System.Collections.Generic.IEnumerable1 [System.Object]'的表达式”。


我们可以在 EF Where 中使用扩展方法吗?请就此给我建议。


叮当猫咪
浏览 260回答 2
2回答

回首忆惘然

首先很抱歉来晚了...但正如 Gert Arnold 所说,这一切都会在记忆中完成。因此 EF 将获取内存中包含产品评论的整个产品表,这对性能来说可能是灾难性的。您可能想要做的是(2 是更好的方法):如果您真的想继续使用您的扩展方法,请将产品和产品评论中所需的属性投影到虚拟机中,然后进行过滤。只需使用 sql 为您提供的平均方法

慕尼黑的夜晚无繁华

EF 中的扩展方法没有问题。该错误与错误的数据类型有关。所以请尝试这种方式public static class Extensions{&nbsp; &nbsp; public static decimal CalculateAverageRating(this IAsyncEnumerable<ProductReview> productReviews)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Calculate and return average rating&nbsp; &nbsp; &nbsp; &nbsp; return averageRatings;&nbsp; &nbsp; }}var products = _context.Products&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Include(pr => pr.ProductReviews)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .AsQueryable().ToAsyncEnumerable();&nbsp; &nbsp; &nbsp; &nbsp; if(searchParams.Rating != 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; products = products.Where(p => p.ProductReviews.CalculateAverageRating() == searchParams.Rating);PS:我没有检查上面的代码
打开App,查看更多内容
随时随地看视频慕课网APP