Tuesday, December 4, 2012

Selecting Data by Joining Tables using ADO.Net Entity Framework

In order to select data from a Model
using the ADO.Net Entity Data Model, we should first create an ADO.Net Entity
Data Model class, refer to the post Creating your First ADO.Net Entity Data Model
to see on how to create an ADO.Net Entity Data Model, that maps to the physical
database.

Once you have created the ADO.Net Entity Data Model class, we can
proceed with querying the model to select data. In this post we shall see on
how to use the ADO.Net Entity Data Model to query the data from more
than 1 underlying physical database and display the results of the query in a
GridView.

1. Create a new .aspx page, I have created a page ViewEmployees.aspx
2. Add a GridView control to the page, which will display
the results of the Select Query.
3. Add the necessary Bound and Template columns to the Grid.

<asp:GridView

ID="grdEmployees"

runat="server"

CellPadding="2"

CellSpacing="2"

HeaderStyle-Font-Names="Verdana"

HeaderStyle-Font-Size="15px"

HeaderStyle-BackColor="Silver"

RowStyle-Font-Names="Verdana"

RowStyle-Font-Size="14px"

AutoGenerateColumns="false"onrowcommand="grdEmployees_RowCommand">

<Columns>

<asp:BoundFieldDataField="ID"HeaderText="Employee ID"/>

<asp:BoundFieldDataField="Name"HeaderText="Name"/>

<asp:BoundFieldDataField="Phone"HeaderText="Phone"/>

<asp:BoundFieldDataField="DepartmentName"HeaderText="Department"/>

<asp:BoundFieldDataField="Salery"HeaderText="Salery"/>

<asp:TemplateFieldHeaderText="EDIT">

<ItemTemplate>

<ahref="ViewEmployees.aspx?ID=<%#Eval("ID")

%>">EDIT</a>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="DELETE">

<ItemTemplate>

<asp:LinkButtonID="lnkDelete"runat="server"

CausesValidation="false"CommandArgument='<%#Eval("ID")
%>'

CommandName="lnkDeleteButton"OnClientClick="return confirm('Are You Sure, You Want to Delete
this Employee?');"

Text="DELETE">

</asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

4.
Once we have the Grid in place, we shall switch to the code-behind to use the ADO.Net
Entity Data Model to query the database.
5. Add a reference to the ADO.Net Entity Data Model