Unable to create a constant value of type 'Closure type'.异常,如何解决?

[已解决] Unable to create a constant value of type 'Closure type'.异常,如何解决?

0
[软件及编程 > C# > LINQ > LINQ to Entities]
使用Linq to Entities的时候发生如下异常:
Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

这是什么原因呢?

我的代码是这样的:
ctx.Products.Where(p => p.Status == (int)s).ToString();

其中s是类型为ProdcutStatus的枚举类型:
public enum ProdcutStatus{
Open,
Close
}

如果不加这个Where就没有错,所以猜想是Where(p => p.Status == (int)s)中间的问题,请问这是什么问题呢?如何解决?
提问时间:2010/4/19 17:22:39 | 提问者:GaLiJiKuai | 悬赏:0 | 浏览:854
最佳答案
这是因为Linq to Entities根据Where中的委托生成SQL语句,所以对里面的复杂程度(方法)有一定的限制,其中的(int)s就无法被正确翻译。
要解决这个问题,需要把这个(int)s过程放到外面来:

int status = (int)s;
ctx.Products.Where(p => p.Status == status).ToString();

这样Where内部还是保持了相对的“干净”,不会阻碍SQL语句的动态生成。
回答时间:2010/4/19 17:29:44 | 回答者:zsu
其他参考答案(0)
提交失败!请检查错误!错误信息:

注:以上所有信息由网友提供,仅供交流、参考,均不代表盛派网络言论,如果有任何问题或不妥,请立即联系我们

以下信息或许对您有用: