C# – Method GetPrice() cannot be translated into a store expression

centity-frameworklinqlinq-to-entitiesnet

I have a class method:

public static class ProductExtensions {

    public static decimal GetPrice(this Product product, Guid rateId) {

        return product.Prices
            .Where(p => p.Rate.RateId == rateId)
            .Select(b => b.UnitPrice)
            .DefaultIfEmpty(product.UnitPrice)
            .First();
    }
 }

and evaluating of an expression

        decimal? total = 
            (from cartItems in storeDB.Carts
            where cartItems.CartId == shoppingCartId
            select (int?)cartItems.Count * cartItems.Product.GetPrice(store.RateId))
            .Sum();

throw an exception:

LINQ to Entities does not recognize the method 'System.Decimal GetPrice(System.Guid)' method, and this method cannot be translated into a store expression.

I am using this very same code in other places and works just fine :

        // Get the price for given rate
        decimal price = product.GetPrice(rate.RateId);

Any idea how to solve it?

Best Answer

Try that:

    decimal? total = 
        (from cartItems in storeDB.Carts
        where cartItems.CartId == shoppingCartId
        select new { cartItems.Count, cartItems.Product})
        .AsEnumerable()
        .Sum(x => (int?)x.Count * cart.Product.GetPrice(store.RateId));

GetPrice has no equivalent in SQL, so you need to execute it on the result, not directly in the query. AsEnumerable forces Linq to consider the query as an IEnumerable (rather that IQueryable) from this point, so what comes next is executed in memory, not in the DB.