How to insert a method inside a LINQ lambda extension method

半城伤御伤魂 提交于 2019-12-08 04:43:31

问题


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.


回答1:


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




回答2:


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))


来源:https://stackoverflow.com/questions/9784746/how-to-insert-a-method-inside-a-linq-lambda-extension-method

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