CiccioMiami
CiccioMiami

Reputation: 8256

How to insert a method inside a LINQ lambda extension method

I have to place a method inside a LINQ lambda. I have the following code:

string productName = "Some product";

searchShoppingCart = shoppingCart.Where(m => productName.Equals(_ProductRepository.GetProductName(m.Id)));

Basically this code is used to select all the shoppingCart instances that contain productName.

The method string GetProductName(int shoppingCartId) is a method from _ProductRepository that returns the name of one product. How this method is implemented and its logic does not matter.

The problem is that LINQ throws an exception. I know the reasons why this exception is thrown, I just would like to know a workaround. I tried

var productContained = shoppingCart.Select(sc => new
                    {
                        scId = sc.Id,
                        productName = _ProductRepository.GetProductName(sc.Id)
                    });

searchShoppingCart = shoppingCart.Where(sc => sc.Id.Equals(productContained.Where(pc => pc.productName.Equals(productName))
                                                                           .Select(pc => pc.Id)));

but it gives me the same exception. Is there any other workaround?

UPDATE

The exception thrown is

LINQ to Entities does not recognize the method 'System.String GetProductName(Int32)' method, and this method cannot be translated into a store expression.

Upvotes: 1

Views: 1442

Answers (2)

VinayC
VinayC

Reputation: 49165

If your are working IQueryable (which I believe that you do) then a call to custom .NET method cannot be translated into the query - that's the reason you get exception.

The work-around would be to fetch all possible shopping carts then apply your method on in-memory product list - for example,

searchShoppingCart = shoppingCart.ToList().Where(m => productName.Equals(_ProductRepository.GetProductName(m.Id)))

Of course, this sucks as it defeats the whole purpose!

Better work-around would be to expose product navigable property within shopping cart object and use the same - for example,

searchShoppingCart = shoppingCart.Where(m => productName.Equals(m.Product.Name))

Upvotes: 0

Adriano Repetti
Adriano Repetti

Reputation: 67080

It throws an exception because it tries to convert your code to SQL (and it can't do it). Read this article for some workarounds: http://thoai-nguyen.blogspot.it/2011/05/custom-function-entity-framework.html

Upvotes: 2

Related Questions