none
Help with LINQ query with relationship RRS feed

  • Question

  •  

    So I have the following tables with one to many relationship:

     

    posts

    ------

    post_id

    post_title

    post_date

     

    comments

    ---------

    comment_id

    post_id

    comment_title

    comment_date

     

    I want to write a linq query to return posts less then or equal to a certain date, but also related comments that are less then or equal then specified date.

     

    What I have is this:

    Code Snippet

    var posts = from p in db.posts
                where p.post_date <= DateTime.Now
                orderby p.post_date descending
                select p);

     

     

    How can I limit which comments get returned for each post?

     

    Thanks,

    Alex

    Thursday, June 26, 2008 5:24 PM

Answers

  • Use the DataLoadOptions object and AssociateWith

     

    MyDataContext db = ...;

    DataLoadOptions options = new DataLoadOptions();

    options.AssociateWith<Post>(p => p.Comments.Where(c => c.comment_date <= DateTime.Now));

    db.LoadOptions = options;

     

     

     

    Thursday, June 26, 2008 8:13 PM
    Moderator