Thursday 18 October 2012

Entity Framework, Nested Controls, Nested Datasources

Well after lots of searching for a decent example of how to nest entity items using entity framework I ended up with my own solution after many painful hours.

The following code, passes a parameter/value through from a control the nested datasource and then in turn populates the control.  This is most useful when creating categories.

This is still work in progress, but hopefully it can be useful for those struggling with this entity framework lark as its not the easiest thing to work with.

<!--Categories-->

  <asp:EntityDataSource ID="CategoriesDataSource" runat="server" ConnectionString="name=NewsEntities1"

  DefaultContainerName="NewsEntities1" EnableFlattening="False" EntitySetName="tbl_NewsCategories"

  Select="it.[Category_ID], it.[Category_Title]">

  </asp:EntityDataSource>

 

 

  <asp:Repeater ID="Repeater1" runat="server" DataSourceID="CategoriesDataSource">

  <ItemTemplate>

  <div class="Article">

  <asp:Label ID="CategoryHeading" runat="server"><h2><%# Eval("Category_Title") %></h2></asp:Label>

  <asp:Label ID="CategoryID" runat="server" Text='<%# Eval("Category_ID")%>' Visible="false" />

<!--News Articles-->

  <asp:EntityDataSource ID="NewsDataSource" runat="server" ConnectionString="name=NewsEntities1"

  DefaultContainerName="NewsEntities1" EnableFlattening="False"

  EntitySetName="tbl_News"

  Select="it.[News_ID], it.[Category_ID], it.[Article_Title], it.[Article_Content], it.[Article_Image], it.[Article_Author], it.[Article_CreatedOn]"

  Where="it.[Category_ID] = @CategoryID">

  <SelectParameters>

  <asp:ControlParameter ControlID="CategoryID" Name="CategoryID" DefaultValue="0" Type="Int32" />

  </SelectParameters>

  </asp:EntityDataSource>

 

 

  <asp:ListView ID="ListView1" runat="server" DataSourceID="NewsDataSource" GroupItemCount="3">

  <LayoutTemplate>

<div ID="groupPlaceholder" runat="server">

  </div>

</LayoutTemplate>

<GroupTemplate>

<div ID="itemPlaceholder" runat="server">

  </div>

</GroupTemplate>

  <EmptyItemTemplate>

  <div>

  There are currently no articles for this category.

  </div>

  </EmptyItemTemplate>

  <ItemTemplate>

<div>

<a href="#"><%# Eval("Article_Title") %></a><br />

  <%# Eval("Article_Content") %><br />

  By <%# Eval("Article_Author") %><br /><br />

</div>

</ItemTemplate>

  </asp:ListView>

 

  </div>

  </ItemTemplate>

  </asp:Repeater>

No comments: