linq-to-sqldatacontextiqueryable

When does IQueryable execute the query?


Ive got the following code which I hacked together from website examples. It works nicely but I dont really understand how it works...

public static Func<EuvaTransientDataContext, string, string, int, IQueryable<SecurityAudit>>
    MatchedIPAddressesAuditRecords =
        CompiledQuery.Compile((EuvaTransientDataContext db, string username, string ipAddress, int withinHours) =>
            (from sa in db.SecurityAudits
             where sa.IPAddress == ipAddress &&
                   sa.Username != username &&
                   sa.AuditDateTime >= DateTime.Now.AddHours(withinHours * -1)
             select sa));

I appreciate the code is a bit specific but what I think is happening as follows:

I can now consume this by doing somethign like this (sorry I dont have the exact code to hand)...

IList<SecurityAudit> = someDataContext
              .MatchedIPAddressesAuditRecords("username", "ipaddress", 24)
              .ToList<SecurityAudit>();

What I dont understand is how the IQueryable is working here?

Would be greatful for some explantion on how this is actually working.

Thanks.


Solution

  • CompiledQuery.Compile is called once in the static constructor.
    This method creates an instance of CompiledQuery, saves the query in this instance and returns a reference on its runtime method that will be called by user code.
    When user executes the method the query is compiled (for the first time only) and the method is executed.