views:

27

answers:

1

I have two tables, subscriptions and topics. Each subscription is related to a specific TopicID (PK for topics table). The first query works fine and retrieves the topicID's of all videos that were uploaded today.

The problem occurs when I try and then use the results of query1 as a where-in clause for query 2. I keep receiving object reference not set to instance of an object.

Query 1

IQueryable<int> topics = (from t in dataLayer.Videos
                  where SqlMethods.DateDiffDay(t.DateCreated, DateTime.Today) == 0
                 select t.TopicID).Distinct();

Query 2 (fails)

 IQueryable<Subscription> subs = from s in dataLayer.Subscriptions
                                     where topics.Contains(s.TopicID)
                                     select s;

The Linq query generated when it fails is {Table(Subscription).Where(s => value(EmailSubscribers+<>c__DisplayClass0).topics.Contains(s.TopicID))}

Any insight into this would be appreciated. I have looked at some samples around the net and they all seem to be identical to mine.

+1  A: 

You might need to ToList() your first query so that it is definitely executed.

Graphain
Brilliant Graphain. Works like a champ. Any idea why it doesn't work if the first query does not have .ToList()?
zhx
Because LINQ to SQL is late binding - the SQL call to get data is delayed as long as possible. If you were to iterate over the first query it makes the call, but until then it holds off until you "need" it. ToList() forces an iteration and makes that call. It's interesting that the second query doesn't iterate over the first query but now you know why.
Graphain
Awesome. Thank you for the explanation. I get it now :-)
zhx