LINQ to Entities不识别方法 - Include + Where

3
我有这段正常运作的代码。
var h = db.MyTable.Include("Children").Include("Parent").ToList();

但是当我添加where条件时
var h = db.MyTable.Include("Children").Include("Parent").Where(x => x.Country==Session["country"].ToString()).ToList();

它给我抛出了一个错误。

LINQ to Entities does not recognize the method 'System.Object get_item (System.String)' method , and this method cannot be translated into a store expression.

我怎么重写它?我是初学者:-) 谢谢

2个回答

3
这是由你的Where表达式引起的。你应该只在其中使用变量或调用可转换为SQL的方法。
首先,将你的Session值保存在一个变量中:
var country = Session["country"].ToString();

然后在您的Where表达式中使用country

MSDN提供了一个列表,列出了您可以在LINQ to SQL表达式中使用的方法以及它们如何映射到SQL函数。


如果你有像这样的东西:Session[x.Key],而不是给定的表达式,即我们对参数有依赖,该怎么办? - router

1

try this:

var t = Session["country"].ToString();
var h = db.MyTable.Include("Children").Include("Parent").Where(x => x.Country==t).ToList();

只有活动可以被解析成表达式树,这是您的提供程序支持的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接