views:

64

answers:

3

hey all. Just wanting to know is this the most efficient way of getting values from a db: given;

-----------    ---------------    -------------
| Channel |    |Issue        |    |Topic      |
| path(ck)|    |channelID(fk)|    |issueID(fk)|
-----------    ---------------    -------------
  • One channel has many Issues
  • One Issue has many Topics
  • path is an alternate key

I have written the following linq statment.

var content = (from c in db.Channels
where c.channel_holding_page == path
select new { c, _latestIssue = c.Issues.OrderBy(i => i.issue_created).Where(i => i.issue_isVisible == true).FirstOrDefault(), _topics = c.Issues.OrderBy(i => i.issue_created).Where(i => i.issue_isVisible == true).FirstOrDefault().Topics }).FirstOrDefault();

I want to get(working backwards here) all the topics associated with the latest issue(issue_created) that is set to be public(issue_isVisible) from said channel.

Is this the most efficient way or is there a method that would be quicker then this.

A: 

I think this is what your code is trying to accomplish:

     var channels = db.channels.Where (c => c.channel_holding_page == path);
     var issues = channels.Select (c => new { c, _latestIssue = c.Issues.Where (i => i.issue_isVisible).OrderBy (i => i.issue_created).FirstOrDefault () });
     var result = issues.Select (ci => new { ci.c, ci._latestIssue, ci._latestIssue.Topics }).FirstOrDefault ();

If there will be only one channel that will match the channel_holding_page check, then we can simplify this a bit more since the channels var can be flattened using a FirstOrDefault() right in the first line.

Tarydon
would that then relate to 3 separate calls to the db?
Kieran
No, just one. It's only when you actually try to pull objects out of the enumerators (like channels, issues, results) that the query is actually run.
Tarydon
+1  A: 

Hey,

Sometimes querying down works well, and you can drill up, as in:

from t in Topic
join i in issues
on t.IssueID equals i.IssueID
join c in channels
on i.ChannelID equals c.ChannelID
where c.Chanel_holding_path == path
select new
{
   i.issue_visible,
   c.channelid,
   t.topicID
}

Not exact,but you get the picture. You can drill up which makes it easier to work with objects.

Brian
The code is much cleaner the way you have put it. I agree it is not exactly getting the same result as my example above but all i was after was a methodology thanks :)
Kieran
A: 

I assume when u change places of .Where and .OrderBy it will speed the query up a bit.

citronas
ffs who gave a minus? comments on that please
citronas