views:

80

answers:

1

Hi, 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 am creating a delegate that accepts a number of paremeters and returns an IQuerable typed to SecurityAudit.
  • I am creating a compiled query etc.

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

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

What I dont understand is how the IQueryable is working here? - Am I returning an interface to a query to my calling method? - Where is my compiled query stored and when is it executed? - What is the relevance of returning an interface IQueryable?

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

Thanks.

A: 

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.

Devart