Unable to create a constant value of type 'Closure type'.异常

使用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
}

这是因为Linq to Entities根据Where中的委托生成SQL语句,所以对里面的复杂程度(方法)有一定的限制,其中的(int)s就无法被正确翻译。
要解 决这个问题,需要把这个(int)s过程放到外面来:

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

这样Where内部还是保持了相对的“干净”,不会阻 碍SQL语句的动态生成。

作者:Angelo Lee
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
原文地址:https://www.cnblogs.com/yefengmeander/p/2887770.html