如何在LINQ lambda扩展方法中插入方法 [英] How to insert a method inside a LINQ lambda extension method
问题描述
我必须在LINQ lambda内放置一个方法.我有以下代码:
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)));
基本上,此代码用于选择所有包含productName
的shoppingCart
实例.
Basically this code is used to select all the shoppingCart
instances that contain productName
.
方法string GetProductName(int shoppingCartId)
是_ProductRepository
中的一种方法,它返回一个产品的名称.此方法的实现方式及其逻辑无关紧要.
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.
问题是LINQ抛出异常.我知道引发此异常的原因,我只想知道一种解决方法.我尝试过
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?
更新
抛出的异常是
LINQ to Entities无法识别方法'System.String GetProductName(Int32)',并且该方法无法转换为商店表达式.
推荐答案
它会引发异常,因为它试图将您的代码转换为SQL(并且无法执行).阅读本文以了解一些解决方法: http://thoai- nguyen.blogspot.it/2011/05/custom-function-entity-framework.html
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
这篇关于如何在LINQ lambda扩展方法中插入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!