如何在LINQ lambda扩展方法中插入方法

编程入门 行业动态 更新时间:2024-10-27 20:28:01
本文介绍了如何在LINQ lambda扩展方法中插入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我必须在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(并且无法执行).阅读本文以了解一些解决方法: 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: thoai-nguyen.blogspot.it/2011/05/custom-function-entity-framework.html

更多推荐

如何在LINQ lambda扩展方法中插入方法

本文发布于:2023-10-25 03:12:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525751.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   如何在   LINQ   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!