【问题标题】:Using Results Outside of dbContext in VB.NET在 VB.NET 中使用 dbContext 之外的结果
【发布时间】:2012-03-23 17:52:37
【问题描述】:

假设我有这样的代码:

Using dbContext as mydb_entities = New mydb_entities
   Dim qperson = (From p in dbContext.People _
                  Where p.name = "John" _
                  Select p)
End Using
Using dbContext as yourdb_entities = New yourdb_entities
   Dim qyou = (From p in dbContext.Customer _
               Where p.name = "John" _
               Select p)
End Using

如何比较 qperson 和 qyou 的结果?由于 End Using 执行后结果“消失”?

【问题讨论】:

    标签: asp.net vb.net entity-framework entity-framework-4 linq-to-entities


    【解决方案1】:

    您需要在 using 语句之外声明这两个变量

    Dim qperson As IQueryable(Of Person)
    Dim qyou As IQueryable(Of Customer)
    
    Using dbContext as mydb_entities = New mydb_entities
       qperson = (From p in dbContext.People _
                  Where p.name = "John" _
                  Select p)
    End Using
    Using dbContext as yourdb_entities = New yourdb_entities
       qyou = (From p in dbContext.Customer _
               Where p.name = "John" _
               Select p)
    End Using
    

    【讨论】:

    【解决方案2】:

    这里的关键是知道您的 LINQ 查询何时运行。这行代码执行时:

    qperson = (From p in dbContext.People _ 
              Where p.name = "John" _ 
              Select p) 
    

    没有查询发送到服务器。相反,您会返回一个实现 IQueryable(Of T) 接口的对象,该接口描述了查询是什么。在您开始使用结果之前,查询实际上不会发送到服务器并执行,例如在 For Each 循环中。这称为延迟执行,是 LINQ 的基础。

    那么这对您意味着什么?好吧,这意味着在执行查询之前不得释放上下文。在到目前为止的示例中,这不一定总是正确的。 (嵌套答案可能会这样做,这取决于嵌套 usings 中实际发生的情况。)

    处理此问题的典型方法是强制执行查询以在上下文被释放之前生成结果的内存集合。 ToList() 扩展方法是执行此操作的常用方法。所以,例如:

    Dim qperson As IList(Of Person)           
    Dim qyou As IList(Of Customer)           
    
    Using dbContext as mydb_entities = New mydb_entities           
       qperson = (From p in dbContext.People _           
                  Where p.name = "John" _           
                  Select p).ToList()
    End Using           
    
    Using dbContext as yourdb_entities = New yourdb_entities           
       qyou = (From p in dbContext.Customer _           
               Where p.name = "John" _           
               Select p).ToList()
    End Using           
    

    现在您已经执行了查询,并在上下文被释放之前将结果存入了内存,您可以愉快地用它们做您想做的事情。

    【讨论】:

    • 读完这个问题后,我首先想到的是“使用 .ToList() 来强制执行查询”。
    【解决方案3】:

    在 C# 中,我通常只是嵌套 usings...

    using (var context blahentities())
    {
      using (var context2 blahentities())
      {
    
      }
    }
    

    查看这个在 vb 中的嵌套使用...

    Nested using statements

    【讨论】:

    • 谢谢保罗。这也是我所做的,但是我遇到了传输级别错误,并且似乎连接正在结束,所以我想看看我是否可以将它们解析为单独的未嵌套调用,从而避免这种可能性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多