Question

I am attempting to list a group of Associations, within each association is a 'widget' that is assigned to the association. The list will include the Association name and any widget assigned to it. The catch is that the inner widget list needs to be sorted by DisplaySequence.

EDMX Model Below: EDMX Model

Simplified Repeater Mark-Up

<asp:Repeater ID="rptAssociations" runat="server">
    <ItemTemplate>      
        <div data-type="assn" id="<%# ((Association)Container.DataItem).AssociationID %>">
            <h3 style="margin-top:15px;"><%# ((Association)Container.DataItem).Acronym %> - <%# ((Association)Container.DataItem).Name %></h3> 
            <asp:Repeater runat="server" ID="rptWidgets" DataSource="<%# ((Association)Container.DataItem).AssociationWidgets %>" >
                <HeaderTemplate>                
                    <ul class="WidgetList">
                </HeaderTemplate>
                <ItemTemplate>
                    <li id="<%# ((AssociationWidget)Container.DataItem).DisplaySequence %>"><%# ((AssociationWidget)Container.DataItem).Widget.Name %></li>
                </ItemTemplate>
                <FooterTemplate>
                    </ul>
                </FooterTemplate>
            </asp:Repeater>
        </div>      
    </ItemTemplate>
</asp:Repeater>

Current Query

var associations = (from a in 
    context.Associations.Include("AssociationWidgets")
                        .Include("AssociationWidgets.Widget")
    orderby a.Acronym
    select a).ToList();

rptAssociations.DataSource = associations;
rptAssociations.DataBind();

I am currently able to get the data that I'm looking for with the setup that I have now. I am looking for the most efficient approach to getting this same data, however, having the Widgets listed in the correct display order.

Is there a different approach to the linq query I should take?

Was it helpful?

Solution

I would approach this like this (untested):

var associations = 
    context.Associations.Select( a => 
       new {
          //... specific properties you need 
          AssociationId = a.AssociationId,
          Name = a.Name,
          ... etc
          Widgets = a.AssociateWidgets.OrderBy(aw => aw.DisplaySequence)
                                      .Select(aw => aw.Widget)
       }
    );

Here you'll get a collection of anonymous types. You can use a concrete type such as

public class AssociationInfo
{
    public string Name {get;set;}
    ...
    public IEnumerable<Widget> Widgets{ get;set; }
}

if necessary by replacing 'new {' with 'new AssociationInfo {'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top