tags:

views:

13

answers:

1

Hi,

I am really new to Linq and am using Linq-to-Sql as follows. However in the following example, my where clause never gets executed and the resultant query attempts to fetch all the records from my table, ignoring even the take method.

Can somebody point out as to what i am doing wrong

        var baseQry = db.Table;
        baseQry.Where(a => a.tab_id == theId);
        baseQry.Select(o => new
        {
            o.name,
            o.display_name,
            o.type,
            o.info,                
            time_stamp = (Convert.ToDateTime(o.timestamp).ToLongDateString())
        }).Take(10);

       baseQry.ToList();
+3  A: 

Your second line...

baseQry.Where(a => a.tab_id == theId);

...is essentially a no-op, because the resulting query isn't carried over into your .Select clause.

You need to change it to this:

var baseQry = db.Table;

var results = baseQry
    .Where(a => a.tab_id == theId)
    .Select(o => new
        {
            o.name,
            o.display_name,
            o.type,
            o.info,                
            time_stamp = (Convert.ToDateTime(o.timestamp).ToLongDateString())
        })
    .Take(10)
    .ToList();
Matt Peterson
Thanks Matt, yes that works. The reason why i was trying to break it up is so that i can dynamically add more where clauses depending on user input. Syntactically i believe that my code seems similar to yours but for one small thing, your works whereas mine does not !!.I have looked into using PredicateBuilder and Scott's dynamic linq library but before going into all that, i wanted to try something simple.Any explanation would be greatly appreciated.
Karthik
IQueryable<T> is your friend (http://msdn.microsoft.com/en-us/library/bb351562.aspx). None of the clauses of your query (.Where, .Select, .Take) are actually retrieving data. They are simply building up a query that is then executed when you call ToList(). You'll see this called "deferred execution" in the LINQ world. The nice thing is that as long as you save the return values of your query fragments as IQueryable<T>, you can continue adding to them to further modify your query. I hope I'm explaining that well.
Matt Peterson
Thanks. I was able to use the IQueryable and get it to work. Pretty verbose though. Thanks a lot for your help Matt.
Karthik