locked
Linq2Sql bug with extensions? RRS feed

  • Question

  • I've been testing some Linq2Sql query's and I came over what seems to be a bug with some extensions.


     

    Code Block

    var blogQuery = from b in db.Blogs

     select b;

     

    var blogs = blogQuery.ToList().Take(5);

     

    The above code is fine, and in my test it takes around 150ms to execute.

     

    Code Block

    var blogQuery = from b in db.Blogs

     select b;

     

    var blogs = blogQuery.Take(5).ToList();

     

    This code however seems to take take around 200ms to execute, and with more data in db.Blogs is feels like it runs the linq query twice.


    I'm not sure how, but is there anyway to find out if my last example infact runs two query's to the sql server?

    Wednesday, October 31, 2007 2:51 PM

Answers

  • Hi Tore, There's a quite difference between the two examples you have provided:

    1. the First one, by calling ToListFirst, will run SQL query againest the whole blogs table, then by LINQ to Objects the Take method will return just the first 5 but from the memory. The SQL server in this case did not take much time to create an execution plan.
    2. In the Second one, by calling the Take method first, the LINQ to SQL will generate a different query that will return only the first 5 from the SQL server, which uses ROW_NUMBER functions in SQL 2005 and a quite bigger query for SQL 2000.

    That's why it takes longer to execute the second query.

    To Actually see what's goning on try these things:

    • Set a break point at each query and invistigate the SQL statement before execution.
    • Break the query in to two statenments and create a foreach loop with breakpoints to feel how long the is the list:

    Code Block

    var blogQuery = from b in db.Blogs select b;

    var blogList = blogQuery.ToList();

    var blogs = blogList.Take(5);

     

     

     

    Also

    Code Block

    var blogQuery = from b in db.Blogs select b;

    var blogTake = blogQuery.Take(5);

     

     

    Code Block

    var blogs = blogTake.ToList();

     

     

    • You can also see what actually sent to SQL by setting the DataContext Log Property to a stream like a file, or the consol

    MyDataContext.Log = Console.Out;

    Then Execute your queries.

     

    Wednesday, October 31, 2007 3:32 PM