Working with Many-To-Many relationships using ADO.NET Entity Framework

by Jagadish Pulakhandam on 5/22/2012 10:31:39 AM
Rated 0 from 0 votes
Brief: Demonstrates on designing an entity model with many-to-many relationship and binding the navigation collection properties to ASP.NET data controls.
Posted to: Programming Entity Framework (Basics) - Examples and Videos
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached video demonstrates the following:
  • How to create an entity model based on Many-To-Many relationships (created using foreign keys in database)
  • How to access navigation properties
  • How to bind EntityDataSource to a Repeater
  • How to bind EntityDataSource to a GridView (nested) inside a Repeater
  • How to bind GridView to a collection based navigation property of an entity.
  • How to use "include" property of "EntityDataSource"
  • All of the above, with no code-behind.
Screenshot:



Sample Entity Model created (using Northwind Database):

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
  <!-- EF Runtime content -->
  <edmx:Runtime>
    <!-- SSDL content -->
    <edmx:StorageModels>
      <Schema Namespace="NorthwindModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
        <EntityContainer Name="NorthwindModelStoreContainer">
          <EntitySet Name="Employees" EntityType="NorthwindModel.Store.Employees" store:Type="Tables" Schema="dbo" />
          <EntitySet Name="EmployeeTerritories" EntityType="NorthwindModel.Store.EmployeeTerritories" store:Type="Tables" Schema="dbo" />
          <EntitySet Name="Territories" EntityType="NorthwindModel.Store.Territories" store:Type="Tables" Schema="dbo" />
          <AssociationSet Name="FK_Employees_Employees" Association="NorthwindModel.Store.FK_Employees_Employees">
            <End Role="Employees" EntitySet="Employees" />
            <End Role="Employees1" EntitySet="Employees" />
          </AssociationSet>
          <AssociationSet Name="FK_EmployeeTerritories_Employees" Association="NorthwindModel.Store.FK_EmployeeTerritories_Employees">
            <End Role="Employees" EntitySet="Employees" />
            <End Role="EmployeeTerritories" EntitySet="EmployeeTerritories" />
          </AssociationSet>
          <AssociationSet Name="FK_EmployeeTerritories_Territories" Association="NorthwindModel.Store.FK_EmployeeTerritories_Territories">
            <End Role="Territories" EntitySet="Territories" />
            <End Role="EmployeeTerritories" EntitySet="EmployeeTerritories" />
          </AssociationSet>
        </EntityContainer>
        <EntityType Name="Employees">
          <Key>
            <PropertyRef Name="EmployeeID" />
          </Key>
          <Property Name="EmployeeID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
          <Property Name="LastName" Type="nvarchar" Nullable="false" MaxLength="20" />
          <Property Name="FirstName" Type="nvarchar" Nullable="false" MaxLength="10" />
          <Property Name="Title" Type="nvarchar" MaxLength="30" />
          <Property Name="TitleOfCourtesy" Type="nvarchar" MaxLength="25" />
          <Property Name="BirthDate" Type="datetime" />
          <Property Name="HireDate" Type="datetime" />
          <Property Name="Address" Type="nvarchar" MaxLength="60" />
          <Property Name="City" Type="nvarchar" MaxLength="15" />
          <Property Name="Region" Type="nvarchar" MaxLength="15" />
          <Property Name="PostalCode" Type="nvarchar" MaxLength="10" />
          <Property Name="Country" Type="nvarchar" MaxLength="15" />
          <Property Name="HomePhone" Type="nvarchar" MaxLength="24" />
          <Property Name="Extension" Type="nvarchar" MaxLength="4" />
          <Property Name="Photo" Type="image" />
          <Property Name="Notes" Type="ntext" />
          <Property Name="ReportsTo" Type="int" />
          <Property Name="PhotoPath" Type="nvarchar" MaxLength="255" />
        </EntityType>
        <EntityType Name="EmployeeTerritories">
          <Key>
            <PropertyRef Name="EmployeeID" />
            <PropertyRef Name="TerritoryID" />
          </Key>
          <Property Name="EmployeeID" Type="int" Nullable="false" />
          <Property Name="TerritoryID" Type="nvarchar" Nullable="false" MaxLength="20" />
        </EntityType>
        <EntityType Name="Territories">
          <Key>
            <PropertyRef Name="TerritoryID" />
          </Key>
          <Property Name="TerritoryID" Type="nvarchar" Nullable="false" MaxLength="20" />
          <Property Name="TerritoryDescription" Type="nchar" Nullable="false" MaxLength="50" />
          <Property Name="RegionID" Type="int" Nullable="false" />
        </EntityType>
        <Association Name="FK_Employees_Employees">
          <End Role="Employees" Type="NorthwindModel.Store.Employees" Multiplicity="0..1" />
          <End Role="Employees1" Type="NorthwindModel.Store.Employees" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="Employees">
              <PropertyRef Name="EmployeeID" />
            </Principal>
            <Dependent Role="Employees1">
              <PropertyRef Name="ReportsTo" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="FK_EmployeeTerritories_Employees">
          <End Role="Employees" Type="NorthwindModel.Store.Employees" Multiplicity="1" />
          <End Role="EmployeeTerritories" Type="NorthwindModel.Store.EmployeeTerritories" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="Employees">
              <PropertyRef Name="EmployeeID" />
            </Principal>
            <Dependent Role="EmployeeTerritories">
              <PropertyRef Name="EmployeeID" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="FK_EmployeeTerritories_Territories">
          <End Role="Territories" Type="NorthwindModel.Store.Territories" Multiplicity="1" />
          <End Role="EmployeeTerritories" Type="NorthwindModel.Store.EmployeeTerritories" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="Territories">
              <PropertyRef Name="TerritoryID" />
            </Principal>
            <Dependent Role="EmployeeTerritories">
              <PropertyRef Name="TerritoryID" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
      </Schema>
    </edmx:StorageModels>
    <!-- CSDL content -->
    <edmx:ConceptualModels>
      <Schema Namespace="NorthwindModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
        <EntityContainer Name="NorthwindEntities" annotation:LazyLoadingEnabled="true">
          <EntitySet Name="Employees" EntityType="NorthwindModel.Employee" />
          <EntitySet Name="Territories" EntityType="NorthwindModel.Territory" />
          <AssociationSet Name="FK_Employees_Employees" Association="NorthwindModel.FK_Employees_Employees">
            <End Role="Employees" EntitySet="Employees" />
            <End Role="Employees1" EntitySet="Employees" />
          </AssociationSet>
          <AssociationSet Name="EmployeeTerritories" Association="NorthwindModel.EmployeeTerritories">
            <End Role="Employees" EntitySet="Employees" />
            <End Role="Territories" EntitySet="Territories" />
          </AssociationSet>
        </EntityContainer>
        <EntityType Name="Employee">
          <Key>
            <PropertyRef Name="EmployeeID" />
          </Key>
          <Property Name="EmployeeID" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
          <Property Name="LastName" Type="String" Nullable="false" MaxLength="20" Unicode="true" FixedLength="false" />
          <Property Name="FirstName" Type="String" Nullable="false" MaxLength="10" Unicode="true" FixedLength="false" />
          <Property Name="Title" Type="String" MaxLength="30" Unicode="true" FixedLength="false" />
          <Property Name="TitleOfCourtesy" Type="String" MaxLength="25" Unicode="true" FixedLength="false" />
          <Property Name="BirthDate" Type="DateTime" />
          <Property Name="HireDate" Type="DateTime" />
          <Property Name="Address" Type="String" MaxLength="60" Unicode="true" FixedLength="false" />
          <Property Name="City" Type="String" MaxLength="15" Unicode="true" FixedLength="false" />
          <Property Name="Region" Type="String" MaxLength="15" Unicode="true" FixedLength="false" />
          <Property Name="PostalCode" Type="String" MaxLength="10" Unicode="true" FixedLength="false" />
          <Property Name="Country" Type="String" MaxLength="15" Unicode="true" FixedLength="false" />
          <Property Name="HomePhone" Type="String" MaxLength="24" Unicode="true" FixedLength="false" />
          <Property Name="Extension" Type="String" MaxLength="4" Unicode="true" FixedLength="false" />
          <Property Name="Photo" Type="Binary" MaxLength="Max" FixedLength="false" />
          <Property Name="Notes" Type="String" MaxLength="Max" Unicode="true" FixedLength="false" />
          <Property Name="ReportsTo" Type="Int32" />
          <Property Name="PhotoPath" Type="String" MaxLength="255" Unicode="true" FixedLength="false" />
          <NavigationProperty Name="Employees1" Relationship="NorthwindModel.FK_Employees_Employees" FromRole="Employees" ToRole="Employees1" />
          <NavigationProperty Name="Employee1" Relationship="NorthwindModel.FK_Employees_Employees" FromRole="Employees1" ToRole="Employees" />
          <NavigationProperty Name="Territories" Relationship="NorthwindModel.EmployeeTerritories" FromRole="Employees" ToRole="Territories" />
        </EntityType>
        <EntityType Name="Territory">
          <Key>
            <PropertyRef Name="TerritoryID" />
          </Key>
          <Property Name="TerritoryID" Type="String" Nullable="false" MaxLength="20" Unicode="true" FixedLength="false" />
          <Property Name="TerritoryDescription" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="true" />
          <Property Name="RegionID" Type="Int32" Nullable="false" />
          <NavigationProperty Name="Employees" Relationship="NorthwindModel.EmployeeTerritories" FromRole="Territories" ToRole="Employees" />
        </EntityType>
        <Association Name="FK_Employees_Employees">
          <End Role="Employees" Type="NorthwindModel.Employee" Multiplicity="0..1" />
          <End Role="Employees1" Type="NorthwindModel.Employee" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="Employees">
              <PropertyRef Name="EmployeeID" />
            </Principal>
            <Dependent Role="Employees1">
              <PropertyRef Name="ReportsTo" />
            </Dependent>
          </ReferentialConstraint>
        </Association>
        <Association Name="EmployeeTerritories">
          <End Role="Employees" Type="NorthwindModel.Employee" Multiplicity="*" />
          <End Role="Territories" Type="NorthwindModel.Territory" Multiplicity="*" />
        </Association>
      </Schema>
    </edmx:ConceptualModels>
    <!-- C-S mapping content -->
    <edmx:Mappings>
      <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
        <EntityContainerMapping StorageEntityContainer="NorthwindModelStoreContainer" CdmEntityContainer="NorthwindEntities">
          <EntitySetMapping Name="Employees"><EntityTypeMapping TypeName="NorthwindModel.Employee"><MappingFragment StoreEntitySet="Employees">
            <ScalarProperty Name="EmployeeID" ColumnName="EmployeeID" />
            <ScalarProperty Name="LastName" ColumnName="LastName" />
            <ScalarProperty Name="FirstName" ColumnName="FirstName" />
            <ScalarProperty Name="Title" ColumnName="Title" />
            <ScalarProperty Name="TitleOfCourtesy" ColumnName="TitleOfCourtesy" />
            <ScalarProperty Name="BirthDate" ColumnName="BirthDate" />
            <ScalarProperty Name="HireDate" ColumnName="HireDate" />
            <ScalarProperty Name="Address" ColumnName="Address" />
            <ScalarProperty Name="City" ColumnName="City" />
            <ScalarProperty Name="Region" ColumnName="Region" />
            <ScalarProperty Name="PostalCode" ColumnName="PostalCode" />
            <ScalarProperty Name="Country" ColumnName="Country" />
            <ScalarProperty Name="HomePhone" ColumnName="HomePhone" />
            <ScalarProperty Name="Extension" ColumnName="Extension" />
            <ScalarProperty Name="Photo" ColumnName="Photo" />
            <ScalarProperty Name="Notes" ColumnName="Notes" />
            <ScalarProperty Name="ReportsTo" ColumnName="ReportsTo" />
            <ScalarProperty Name="PhotoPath" ColumnName="PhotoPath" />
          </MappingFragment></EntityTypeMapping></EntitySetMapping>
          <EntitySetMapping Name="Territories"><EntityTypeMapping TypeName="NorthwindModel.Territory"><MappingFragment StoreEntitySet="Territories">
            <ScalarProperty Name="TerritoryID" ColumnName="TerritoryID" />
            <ScalarProperty Name="TerritoryDescription" ColumnName="TerritoryDescription" />
            <ScalarProperty Name="RegionID" ColumnName="RegionID" />
          </MappingFragment></EntityTypeMapping></EntitySetMapping>
          <AssociationSetMapping Name="EmployeeTerritories" TypeName="NorthwindModel.EmployeeTerritories" StoreEntitySet="EmployeeTerritories">
            <EndProperty Name="Employees">
              <ScalarProperty Name="EmployeeID" ColumnName="EmployeeID" />
            </EndProperty>
            <EndProperty Name="Territories">
              <ScalarProperty Name="TerritoryID" ColumnName="TerritoryID" />
            </EndProperty>
          </AssociationSetMapping>
        </EntityContainerMapping>
      </Mapping>
    </edmx:Mappings>
  </edmx:Runtime>
</edmx:Edmx>

ASP.NET markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td valign="top">
                    <table>
                        <asp:Repeater ID="Repeater2" runat="server" DataSourceID="EntityDataSource2">
                            <ItemTemplate>
                                <tr>
                                    <td>
                                        Territory:
                                    </td>
                                    <td>
                                        <%# DataBinder.Eval(Container.DataItem, "TerritoryDescription")%>
                                        (ID:
                                        <%# DataBinder.Eval(Container.DataItem, "TerritoryID")%>
                                        )
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2">
                                        <asp:GridView ID="GridView1" runat="server" DataSource='<%# ((WebApplication1.Territory)Container.DataItem).Employees %>'
                                        AutoGenerateColumns="False">
                                            <Columns>
                                                <asp:BoundField DataField="EmployeeID" HeaderText="ID" />
                                                <asp:BoundField DataField="FirstName" HeaderText="Name" />
                                            </Columns>
                                        </asp:GridView>
                                    </td>
                                </tr>
                            </ItemTemplate>
                        </asp:Repeater>
                    </table>
                    <asp:EntityDataSource ID="EntityDataSource2" runat="server" ConnectionString="name=NorthwindEntities"
                        DefaultContainerName="NorthwindEntities" EnableFlattening="False" EntitySetName="Territories"
                        Include="Employees">
                    </asp:EntityDataSource>
                </td>
                <td valign="top">
                    <table>
                        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="EntityDataSource1">
                            <ItemTemplate>
                                <tr>
                                    <td>
                                        Employee:
                                    </td>
                                    <td>
                                        <%# DataBinder.Eval(Container.DataItem, "LastName") %>
                                        (ID:
                                        <%# DataBinder.Eval(Container.DataItem, "EmployeeID") %>
                                        )
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2">
                                        <asp:GridView ID="GridView1" runat="server" DataSource='<%# ((WebApplication1.Employee)Container.DataItem).Territories %>'>
                                        </asp:GridView>
                                    </td>
                                </tr>
                            </ItemTemplate>
                        </asp:Repeater>
                    </table>
                    <asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=NorthwindEntities"
                        DefaultContainerName="NorthwindEntities" EnableFlattening="False" EntitySetName="Employees"
                        Include="Territories">
                    </asp:EntityDataSource>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following

Video/Screen Recording (may not have audio narration/annotations)
You need to Login or Join for FREE to download the following