为什么不能从编译查询中返回列表

为什么不能从编译查询中返回列表

本文介绍了为什么不能从编译查询中返回列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用编译查询来一遍又一遍地查询来加快我的应用程序的速度.

I was speeding up my app by using compiled queries for queries which were getting hit over and over.

我试图这样实现:

Function Select(ByVal fk_id As Integer) As List(SomeEntity)
    Using db As New DataContext()
        db.ObjectTrackingEnabled = False
        Return CompiledSelect(db, fk_id)
    End Using
End Function

Shared CompiledSelect As Func(Of DataContext, Integer, List(Of SomeEntity)) = _
    CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _
         (From u In db.SomeEntities _
          Where u.SomeLinkedEntity.ID = fk_id _
          Select u).ToList())

这不起作用,我收到了此错误消息:

This did not work and I got this error message:

Type : System.ArgumentNullException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Value cannot be null.
Parameter name: value

但是,当我更改编译查询以返回IQueryable而不是List时,就像这样:

However, when I changed my compiled query to return IQueryable instead of List like so:

Function Select(ByVal fk_id As Integer) As List(SomeEntity)
    Using db As New DataContext()
        db.ObjectTrackingEnabled = False
        Return CompiledSelect(db, fk_id).ToList()
    End Using
End Function

Shared CompiledSelect As Func(Of DataContext, Integer, IQueryable(Of SomeEntity)) = _
    CompiledQuery.Compile(Function(db As DataContext, fk_id As Integer) _
         From u In db.SomeEntities _
         Where u.SomeLinkedEntity.ID = fk_id _
         Select u)

效果很好.谁能阐明这是为什么?

It worked fine. Can anyone shed any light as to why this is?

顺便说一句,已编译的查询很糟糕!他们使我的应用程序加速了2倍.

BTW, compiled queries rock! They sped up my app by a factor of 2.

推荐答案

猜测是因为可以延迟加载返回IQueryable的已编译查询,而返回List的已编译查询强制在加载类时对查询进行评估(即对Shared成员进行评估时).很可能在类加载时,您的数据库连接未建立,因此查询评估失败.

At a guess, this may be because the compiled query that returns an IQueryable can be lazy-loaded, whereas the compiled query that returns a List forces the query to be evaluated when the class is loaded (which is when Shared members are evaluated). Quite probably, at class load time, your database connection isn't set up, so evaluation of the query fails.

尝试将CompiledSelect的声明更改为Shared 属性,并在其中放置一个断点,以查看每种情况下何时对其进行实际评估.

Try changing the declaration of CompiledSelect to a Shared property, and put a breakpoint in it to see when it is actually evaluated in each case.

这篇关于为什么不能从编译查询中返回列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:42