我有一个正在尝试查询的数据上下文,我想在单击按钮时将其结果绑定(bind)到 GridView 。连接到数据上下文效果很好。我得到了我期望的 1000 条记录。当我尝试添加 WHERE 子句时,遇到了问题。这是我试图让它发生的按钮事件:
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim dsource = New MY_DataContext().SV_XXXs '--- This works, the data is all there
gridRec.DataSource = dsource.ToList().Where(Function(dtable) dtable.PN = Session("PN")) '--- this fails
'--- Also tried this, it also did not work ----------------------------------------------------------
'--- gridRec.DataSource = dsource.Where(Function(dtable) dtable.PN = Session("PN")) '--- this fails
'----------------------------------------------------------------------------------------------------
gridRec.DataBind()
End Sub
session 变量有效并且数据源填充正确,但是当它尝试执行Where子句时出现以下错误:
Evaluation of method System.Linq.SystemCore_EnumerableDebugView`1[SV_REC].get_Items() calls into native method System.WeakReference.get_Target(). Evaluation of native methods in this context is not supported.
还尝试过:
Dim results =
(
From T In dsource
Where T.PN = Session("SAFRReceiverPN")
Select T
).ToList
并收到此错误
Method 'System.Object CompareObjectEqual(System.Object, System.Object, Boolean)' has no supported translation to SQL.
并尝试过:
Dim results = From t In dsource Where (t.PN = Session("SAFRReceiverPN")) Select t
尝试 WHERE 子句时似乎没有任何效果
如果您有任何建议,C# 或 VB.NET 都很酷。 真的,非常感谢任何帮助,谢谢。
最佳答案
当您尝试访问查询内的 session 时,LINQ to SQL 不知道该怎么做。与其这样做,不如在查询之前从 session 中获取值并将结果存储在本地变量中,然后在查询中使用该本地变量。例如,在 C# 中:
var receiver = (string) Session["SAFRReceiverPN"];
var results = dsource.Where(t => t.PN == receiver);
(当您只是尝试执行简单的过滤器时,我不会理会查询表达式。)
关于asp.net - 在 Linq-to-SQL 中使用 WHERE 子句时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47872165/