7

In a website, if I have a class:

public class Provider
{
    static readonly Func<Entities, IEnumerable<Tag>> AllTags =
        CompiledQuery.Compile<Entities, IEnumerable<Tag>>
        (
            e => e.Tags
        );

    public IEnumerable<Tag> GetAll()
    {
        using (var db = new Entities())
        {
            return AllTags(db).ToList();
        }
    }
}

In a page I have:

protected void Page_Load(object sender, EventArgs ev)
{
    (new Provider()).GetAll();
}

How many times the query will be compiled? Every time the page loads...? Once in the application...?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • @Martinho Fernandes: That is only half the question... You are (wrongly) assuming the OP is not aware how static fields work in ASP.NET. – leppie Feb 08 '11 at 12:12
  • It seems like you're already getting the answer to this question in the answers to [your last question](http://stackoverflow.com/questions/4932594/when-should-i-use-a-compiledquery). What are you trying to ask differently here? – Cody Gray - on strike Feb 08 '11 at 12:19
  • @Cody Gray, nice edit! Thank you! :) – BrunoLM Feb 08 '11 at 12:19
  • @Cody, I think this question wasn't very clear over there, I decided to elaborate on it. The answers here regarding this are more focused... – BrunoLM Feb 08 '11 at 12:23

5 Answers5

4

since it is a static member, once when class is loaded in app domain.

Mubashir Khan
  • 1,464
  • 1
  • 12
  • 17
1

Seeing it is compiled. I would say once. Why would it need to be recompiled? Isn't that the point of compiled queries?

Given the compiled query is static, once per application instance/lifetime. Note: Lifetimes may overlap.

leppie
  • 115,091
  • 17
  • 196
  • 297
1

I'd say once per AppDomain, since it's a static variable.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
1

If you define your AllTags query this way it will be compiled only once. Check this blog post about compiled queries in Web applications and web services by Julie Lerman.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
-1

http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx#Y696

"Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called."

So it will compile at most each time the page is loaded. Since your class doesn't have a static constructor, it shouldn't compile until you actually access the static member. (According to MSDN.)

However, does that compile? It appears you are trying to load a static member from an instantiated class.

William
  • 290
  • 1
  • 3
  • 9
  • I didn't say it was mandatory. I said he didn't have one. And according to the documentation, that means it doesn't set up the static fields until they are used. – William Feb 08 '11 at 17:26