When does a compiled query that returns an IQuerya

2019-04-29 01:35发布

Okay I need a sanity check here...

I've compiled a query that returns an IQueryable when executed.

On what line(s) should the query actually execute against the database in the following example?

101 IQueryable<T> results = MyCompiledQuery(MyDataContext);
102 List<T> final = (from t in result
103                  where t.ID > 5
104                  select t).ToList<T>();

Here is how I define the compiled query

 public static Func<MyDataContext, IQueryable<Widget>> MyCompiledQuery=
        CompiledQuery.Compile<MyDataContext, IQueryable<Widget>>(
                      (MyDataContext db) =>
                      from w in db.Widgets
                      where ((w.Type == WidgetType.Atype ||  //Widget.Atype is a Linq to Sql object, that I've defined statically
                              w.Type == WidgetType.Btype ||  //See above comment
                              w.Type == WidgetType.Ctype ) && //See above comment
                              w.Location == WidgetLocation.Domestic)  //Samething applies here
                        select euc);

FOR ADDITIONAL DISCUSSION PLEASE REFER TO: LINQ to SQL compiled queries and when they execute

5条回答
叛逆
2楼-- · 2019-04-29 01:46

This Query executes on line 101. I verified it by doing a SQL Profiler trace. I guess this is because it is a compiled query.

The filtering you are doing afterwords > 5 is done in memory.

查看更多
爷的心禁止访问
3楼-- · 2019-04-29 01:51

"On the line 104, when doing ToList conversion."

Well, this answer is incorrect. We invoke delegate stored in MyCompiledQuery variable on line 101 that returns the result of the compiled query, not the query itself.

查看更多
一纸荒年 Trace。
4楼-- · 2019-04-29 01:53

It executes at line 104 (when you call ToList()).

A compiled query is a query that is translated only once to TSQL at compile time, instead of everytime prior to execution.

查看更多
我只想做你的唯一
5楼-- · 2019-04-29 02:09

As far as I know IQueryable never gets executed it just converts the Linq query to a queryable format so that it gets executed whenever its requested.

In this case I guess the moment its asked to convert to a List it queries the result. And no point in fight about line 102 and 104 as both represents a single line.

查看更多
可以哭但决不认输i
6楼-- · 2019-04-29 02:11

This is called Deferred Execution.
You can read a good post on it here.

查看更多
登录 后发表回答