Search code examples
c#asp.netlinqrepeaterasprepeater

Repeater with Linq - One Item with many child items


This is a challenging one.

I have 2 tables in the DB:

Class: Id, Class Name etc.

Student: ID, ClassID, Name etc.

I would like to have a Repeater which contains the following:

Class 1 Name

  • Student 1
  • Student 2

Class 2 Name

  • Student 1
  • Student 2

Now here's my Dilemma.

If I do a Select and Join with Linq something along these lines I get a new repeater Item for every student:

var query = (From c in Class
join s in Student on c.ID equals S.ClassID
select new {C,A}).Tolist();

However what I want is an Item for every CLASS with children items in each class as student.

Not too sure If I explained myself here... Ask questions and I'll answer.

Thank you very very much.


Solution

  • You can use a nested repeater and have the child repeater use the students of the parent class.

    <asp:Repater ....>
     <asp:Repeater runat="server" DataSource='<%# Eval("Students") %>'>
     </>
    

    It depends a bit on your datamodel, but if you have the proper FK structure you do not need to manually join to the new {}. You coud simply force eager loading on the datacontext and do a Foreach over your class

    Code example found here: http://www.antiyes.com/nested-repeater