Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i populate a POCO (child) IList property from a Linq2Sql query?

I have a two classes:

public class Question
{
    public IList<Answer> Answers { get; set; }
}

public class Answer
{ .. }

In my Linq2Sql designer, there's two L2S objects on designer, with the correct 0<->many arrow between them. Kewl.

I'm not sure how i can retrieve these questions/answers in a single call and populate my POCO objects ..

this is what i've got ... can someone fill in the blanks?

public IQueryable<Question> GetQuestions()
{
    return from q in _db.Questions
        select new Question
            {
                Title = q.Title,
                Answers = ????????   // <-- HALP! :)
            };
}

thoughts?

Update : War of the POCO

Thanks for the replies but it's not 100% there yet.

Firstly, i'm returning a POCO class, not the Linq2Sql context class. This is why i'm doing...

select new Question { .. };

that class is POCO, not the linq2sql.

Secondly, I like the answers that point to doing Answers = q.Answers.ToList() but this also will not work because it's trying to set a Linq2Sql class to a POCO class.

like image 414
Pure.Krome Avatar asked Dec 31 '22 07:12

Pure.Krome


1 Answers

If your LINQ to SQL classes have a relationship between them, then an "Answers" property should have been generated on the "Question" LINQ to SQL class. So you should be able to simply do this:

return from q in _db.Questions
       select new Question
       {
           Title = q.Title,
           Answers = q.Answers.ToList(),
       }

You may be able to omit the call to ToList() - I'm not sure what type LINQ to SQL uses for generated related rows (I believe it's IQueryable<T>).

To force the Answers property to be populated up front, rather than firing off another query for each question, you can use the DataLoadOptions class. Essentially you tell LINQ to SQL to load answers any time you query questions (using the LoadWith method - see the MSDN documentation).

Edit

You're right - since your Question.Answers property is a list of your own POCO, assigning it with q.Answers isn't the way to go. This might work better:

return from q in _db.Questions
       select new Question
       {
           Title = q.Title,
           Answers = (from a in q.Answers
                     select new Answer { ... }).ToList(),
       }
like image 195
Matt Hamilton Avatar answered Jan 29 '23 19:01

Matt Hamilton