Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
www.ManzoorTheTrainer.com
Table of Content
About the Author. 3
About the Technical Reviewers And Supporters...4
Chapter 1 : Introduction to Entity Framework.. 5
Chapter 2 : Creating an Entity Data Model. 7
Chapter 3 : Exploring Entity Data Model ..16
Chapter 4: Exploring Entity Data Model in Entity Framework 5.X ..24
Chapter 5 : Performing an Insert Operation ..26
Chapter 6 : Performing a Select Operation .31
Chapter 7 : Performing a Search Operation 34
Chapter 8 : Performing an Update Operation 36
Chapter 9 : Performing a Delete Operation 40
Chapter 10 : Working With Stored Procedures-I 44
Chapter 11 : Working With Stored Procedures-II .52
Chapter 12 : Working With Stored Procedures-III ..57
Chapter 13 : Immediate Mode Vs Differed Mode ..61
Chapter 14 : Working With Transactions 64
Chapter 15 : Working With Navigation Properties ..73
Chapter 16 : Lazy Loading in Entity Framework 76
Chapter 17 : Asp.Net Dynamic Data Entity Website 91
www.ManzoorTheTrainer.com
www.ManzoorTheTrainer.com
www.ManzoorTheTrainer.com
Want easy and automated way of mapping between Objects (Classes) and Relations
(Tables).
Want to eliminate the need for most of the data-access code that developers usually
need to write.
Want to write pure objects, less code and simplify the process of updating the
database.
Want to write C# language syntaxed queries to work with any database with full
intellisense support for columns and tables name.(Strongly Typed)
Using the Entity Framework, developers issue queries using LINQ, then retrieve and
manipulate data as strongly typed objects. The Entity Frameworks ORM
implementation provides services like change tracking, identity resolution, lazy
loading, and query translation so that developers can focus on their applicationspecific business logic rather than the data access fundamentals.
-
www.ManzoorTheTrainer.com
Model First
o
Creating the database from model (Generating Database Tables from Classes
or Class Diagram).
Creating the database from the coded classes(No class diagrams) is POCO.
www.ManzoorTheTrainer.com
In this chapter, Im going to show you How to create your Entity Data Model.
This is very simple. Ive a database called as organization in which Ive department
table and employee table.
Im going to use the same database throughout our course on Entity Framework.
www.ManzoorTheTrainer.com
Lets create our entity data model(EDM) which is the heart of Entity Framework and it
is very simple.
Click Add
www.ManzoorTheTrainer.com
As I want to generate Entity Data Model from an existing database. Select Generate
Empty Database click Next.
Youll see the database is organization and Entity connection string (same as your
connection string which provides the information about the provider, DataSource,
Initial Catalog , UserID, Password, Integrated Security.)
www.ManzoorTheTrainer.com
10
The connection string also contains some extra information as metadata about your
Entity Framework. Save entity connection settings in Web.Config as
OrganizationEntities click next.
At this point Itll retrieve the database information (tables, stored procedures..) As
of now Im going to work with two tables tbl_Dept and tbl_Emp. Im going to add
these two tables to my Entity Data Model
Leave the options checked for Pluralize or Singularize generated object names and
Include foreign key columns in the model click on Finish.
As you might have seen, in a single department I can have n number of employees.
www.ManzoorTheTrainer.com
11
So, weve one-to-many relationship and all the columns that Ive in the database
are turned into properties for both the tables.
There are two extra properties called as Navigation Properties. That means whenever
Ive relation between two tables for navigation from either tbl_Dept to tbl_Emp or
tbl_Emp to tbl_Dept .
Open with XML Editor Click Ok then Yes for Prompt window
This is the XML file that is generated automatically for Entity Data Model
Let us have a look into this XML file and let us see what it contains
1. Runtime tag <edmx:Runtime> and
2. Designer tag <Designer>
www.ManzoorTheTrainer.com
12
The Designer tag contains some UI related to our Entity Data Model (Graphical table
data)
www.ManzoorTheTrainer.com
13
2. CSDL (Conceptual Schema Definition Language) [Properties for each table and each
column.. for C# data]
<edmx:ConceptualModels >
<Schema Namespace="OrganizationModel" Alias="Self "
xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityContainer Name="OrganizationEntities " annotation:LazyLoadingEnabled ="true">
<EntitySet Name="tbl_Dept" EntityType="OrganizationModel.tbl_Dept" />
<EntitySet Name="tbl_Emp" EntityType="OrganizationModel.tbl_Emp" />
<AssociationSet Name="F K_tbl_Emp_tbl_Dept"
Association="OrganizationModel.F K_tbl_Emp_tbl_Dept ">
<End Role="tbl_Dept " EntitySet="tbl_Dept" />
<End Role="tbl_Emp" EntitySet="tbl_Emp" />
</AssociationSet>
<FunctionImport Name="SP_GetAllEmployee "
ReturnType="Collection(OrganizationModel.SP_GetAllEmployee_Result)" />
<FunctionImport Name="SP_GetEmployeesByDid "
ReturnType="Collection(OrganizationModel.SP_GetEmployeesByDid_Result)">
<Parameter Name="Did" Mode="In" Type="Int32" />
</FunctionImport >
<FunctionImport Name="SP_GetEmpNameAndSalaryByEid ">
<Parameter Name="Eid" Mode="In" Type="Int32" />
<Parameter Name="EName " Mode="InOut " Type="String" />
<Parameter Name="ESal" Mode="InOut" Type="Double " />
</FunctionImport >
</EntityContainer>
<EntityType Name="tbl_Dept">
<Key>
<PropertyRef Name="Did" />
</Key>
<Property Name="Did" Type="Int32" Nullable ="false "
annotation:StoreGeneratedPattern="Identity" />
<Property Name="Dname " Type="String" MaxLength="50" Unicode="false " FixedLength="false" />
<Property Name="HOD" Type="String" Nullable="false" MaxLength="50" Unicode="false "
FixedLength="false " />
<Property Name="Gender" Type="String" Nullable ="false" MaxLength="50" Unicode="false"
FixedLength="false " />
<NavigationProperty Name="tbl_Emp" Relationship="OrganizationModel.FK_tbl_Emp_tbl_Dept "
FromRole ="tbl_Dept" ToRole="tbl_Emp" />
<Property Type="Boolean" Name="Active" />
</EntityType>
<EntityType Name="tbl_Emp">
<Key>
<PropertyRef Name="Eid" />
</Key>
<Property Name="Eid" Type="Int32" Nullable ="false "
annotation:StoreGeneratedPattern="Identity" />
<Property Name="EName " Type="String" Nullable ="false" MaxLength="50" Unicode="false "
FixedLength="false " />
<Property Name="ESal" Type="Double " Nullable ="false " />
<Property Name="EGen" Type="String" Nullable ="false" MaxLength="10" Unicode="false "
FixedLength="false " />
<Property Name="EDOB" Type="DateTime" Nullable ="false " />
<Property Name="Did" Type="Int32" />
www.ManzoorTheTrainer.com
14
<NavigationProperty Name="tbl_Dept"
Relationship="OrganizationModel.F K_tbl_Emp_tbl_Dept " FromRole ="tbl_Emp" ToRole="tbl_Dept "
/>
</EntityType>
<Association Name="F K_tbl_Emp_tbl_Dept">
<End Role="tbl_Dept" Type="OrganizationModel.tbl_Dept" Multiplicity="0..1" />
<End Role="tbl_Emp" Type="OrganizationModel.tbl_Emp" Multiplicity="*" />
<ReferentialConstraint >
<Principal Role="tbl_Dept">
<PropertyRef Name="Did" />
</Principal>
<Dependent Role="tbl_Emp">
<PropertyRef Name="Did" />
</Dependent>
</ReferentialConstraint >
</Association>
<ComplexType Name="SP_GetAllEmployee_Result ">
<Property Type="Int32" Name="Eid" Nullable ="false " />
<Property Type="String" Name="EName " Nullable ="false" MaxLength="50" />
<Property Type="Double " Name="Esal" Nullable ="false " />
<Property Type="DateTime" Name="EDOB" Nullable ="false " Precision="23" />
<Property Type="String" Name="Dname" Nullable="true" MaxLength="50" />
<Property Type="String" Name="HOD" Nullable="false " MaxLength="50" />
</ComplexType >
<ComplexType Name="SP_GetEmployeesByDid_Result ">
<Property Type="Int32" Name="Eid" Nullable ="false " />
<Property Type="String" Name="EName " Nullable ="false" MaxLength="50" />
<Property Type="Double " Name="ESal" Nullable ="false " />
<Property Type="String" Name="EGen" Nullable ="false " MaxLength="10" />
<Property Type="DateTime" Name="EDOB" Nullable ="false " Precision="23" />
<Property Type="Int32" Name="Did" Nullable ="true " />
</ComplexType >
</Schema>
</edmx:ConceptualModels >
www.ManzoorTheTrainer.com
15
www.ManzoorTheTrainer.com
16
In this chapter we are going to explore the class that gets generated whenever we
create Entity Data Model
Now, there are two important things that you need to remember from this file
www.ManzoorTheTrainer.com
17
Hope you might have remembered when we were creating Entity Data Model,
In the wizard we gave the name of the model as OrganizationModel.
So OrganizationModel is the namespace.
On the page wherever you need to access the data with the help of Entity
Data Model, You need to say Using OrganizationModel; i.e., you need to add
this namespace on the page wherever you code.
o
o
You need to create the context object whenever you want to work with Entity
Data Model.
So, this class is present in the OrganizationModel namespace thats why we
need to add this namespace and create the object of this class.
www.ManzoorTheTrainer.com
18
Let us see the entities that got created for each table.
So, we should have 2 entities. Entities are nothing but the objects the classes.
o public partial class tbl_Dept : EntityObject
o public partial class tbl_Emp : EntityObject
www.ManzoorTheTrainer.com
19
So, Ive got one entity that is Department tbl_Dept and the other entity that is
tbl_Emp and they contains the properties Did(Department ID) which is of type
int, (DName) Department name, HOD and Gender for tbl_Dept.
www.ManzoorTheTrainer.com
20
It also contains one extra property that is nothing but the Navigation property
that means we say whenever there is a primary and foreign key relationship it is
creating a property that is called as Navigation property.
From department table we can move to Employee table with the help of
Navigation property called as tbl_Emp.
www.ManzoorTheTrainer.com
21
{
get
{
return
((IEntityWithRelationships)this).RelationshipManager.Get RelatedCollection<tbl_Emp>("
OrganizationModel.FK_tbl_Emp_tbl_Dept", "tbl_Emp");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection
<tbl_Emp>("OrganizationModel.FK_tbl_Emp_tbl_Dept", "tbl_Emp", value);
}
}
}
www.ManzoorTheTrainer.com
www.ManzoorTheTrainer.com
22
23
Anyway we are going to see how to use all these things in our future chapters.
So, these are the entities that get created.
Now, operations on these entities are available in this class OrganizationEntities.
So, you have a class which is partial and you have partial methods and you have
objectset properties.
And, the important thing is AddToMethods.
So, AddTotbl_Dept is the method to insert some record into the department
table.
AddTotble_Emp is the method used to insert some record into the Employee table
www.ManzoorTheTrainer.com
24
There are two ways of working with Entity Framework i.e., ObjectContext and
DbContext.
This book deals with ObjectContext.
Now, if at all you are working on Visual Studio 2012 with latest version of Entity
Framework 5.X.
Here are few settings that you need to perform once once you generate your Entity
Data Model or you can say your edmx file to work with ObjectContext.
So, you need to perform two steps.
Right click in edmx file go for properties and say Code Generation Strategy to
Default.
In your OrganizationModel hierarchy youll find two files with .tt extension
www.ManzoorTheTrainer.com
25
Now, you can rebuild the project and youll see that everything is successful.
These are the two steps that you need to perform if at all you want to work with
Entity Framework on Visual Studio 2012.
Now, what are these tt files, how can we work with tt files? All these things we can
see in our next release.
So, in our next Chapters we will see basic operations i.e., performing insert, update,
delete and read operations from Entity Data Model.
www.ManzoorTheTrainer.com
26
In this chapter I am going to show you how to perform the insert operation on Entity
Data Model that is in your Entity Framework.
It is very simple. Say, Ive a form it is a normal ASP.NET form that Ive created to
insert data into the department table.
www.ManzoorTheTrainer.com
27
</tr>
<tr>
<td style="text-align: right">
HOD</td>
<td>
<asp:TextBox ID="txtHOD" runat="server"></asp:Text Box>
</td>
</tr>
<tr>
<td style="text-align: right">
Gender</td>
<td>
<asp:RadioButtonList ID="rblGender" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="M">Male</asp:ListItem>
<asp:ListItem Value="F">Female</asp:ListItem>
</asp:RadioButtonList >
</td>
</tr>
<tr>
<td style="text-align: right">
IsActive</td>
<td>
<asp:CheckBox ID="ckbActive" runat="server" />
</td>
</tr>
<tr>
<td style="text-align: right">
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</td>
<td>
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
<asp:Button ID="btnDelete" runat="server" onclick="btnDelete_Click"
Text="Delete" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center">
<asp:GridView ID="grdDept" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font -Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font -Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font -Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView >
</td>
</tr>
</table>
Next, department name Ive created a textbox for this for HOD Ive a textbox, for
gender Ive a radio button list and for Active flag Ive IsActive checkbox.
Now, on this save button click I need this data to get inserted into this department
table.
www.ManzoorTheTrainer.com
28
As we learnt in our previous chapter if you want to perform anything on Entity Data
Model you need to use a namespace that is nothing but using OrganizationModel;
that weve in our solution explorer In Organization Model.
This is the namespace that we add OrganizationModel. And Ill create an object of
this class that is OrganizationEntities.
OrganizationEntities OE = new OrganizationEntities();
Now I want to perform an insert operation on Department table that means I need to
create the object for tbl_Dept
protected void btnSave_Click(object sender, EventArgs e)
{
OrganizationEntities OE = new OrganizationEntities();
// This is the entity that we got the entity for department table
tbl_Dept d = new tbl_Dept();
//Department ID is auto increment I need not to do anything for this
//HOD Name, txtDName, txtHOD these are all the IDs of the textboxes that we ve on the form
d.Dname = txtDName.Text.ToString();
d.HOD = txtHOD.Text.ToString();
d.Gender = rblGender.SelectedValue.ToString();
//This is of type BooleanWhenever the checkbox is checked I should set it to true else to false
d.Active = ckbActive.Checked;
//Now department object is ready. I need to insert this department d in the department table. So, Ill
//perform that operation with the help of OrganizationEntities object
OE.AddTotbl_Dept(d);
www.ManzoorTheTrainer.com
29
//Finally save changes. It is going to reflect in the database. This is very simple. This is how you can
perform an insert operation.
OE.SaveChanges();
}
Let me right click on the department table and say show table data
www.ManzoorTheTrainer.com
30
Ill say department name as Development, HOD as Long, Gender as male and Ill say
IsActive. Save this.
www.ManzoorTheTrainer.com
31
In this chapter Im going to show you how to perform simple select operation with
the help of your Entity Data Model in Entity Framework.
Here Ive a gridview called as grdDept and I want to load all the departments into
this gridview in my page load event.
Ill just right click and say view code. Ive my page load event. I want to get all the
departments in the page load. So, as I told you I need to add this namespace that
weve added already.
And I need to create the object of Entity Class that is Context Class object.
first I look into the OrganizationEntities Ive a property Object Set Properties region.
In this Ive a property called as tbl_Dept which gives me all the departments which
returns a collection of all the departments.
www.ManzoorTheTrainer.com
Ill say
grdDept.DataSource = OE.tbl_Dept.ToList();
grdDept.DataBind();
If I want to display all the employees again that is very simple Ill say
grdDept.DataSource = OE.tbl_Emp.ToList();
www.ManzoorTheTrainer.com
32
www.ManzoorTheTrainer.com
33
34
That means Ill write a department ID in the textbox txtDid and Ill click on search
button and I want to search the record whose department ID is given in txtDid and I
want to fill the below form.
So, let us see how to perform search operation from your Entity Data Model.
Ill double click on the search button. Search a record is nothing but writing a query
with where clause that is what I want select * from department table where
department id = whatever I give in txtDid textbox.
So, first of all I need to create the object of ContextClass that is
and Im trying to search a record from department table. Ill get an object of type
www.ManzoorTheTrainer.com
35
rblGender.SelectedValue = d.Gender;
ckbActive.Checked = d.Active.Value;
}
Ill execute this. Ill write the department ID as 100 and I should get this record filled
here. Ill say search.
In our next chapter well try to update this as Ive HOD as Long. Ill change it to Mark
and if I say save, this should perform update operation. So, let us see this in our
next chapter.
www.ManzoorTheTrainer.com
36
In this chapter I am going to perform update operation that is first I will search for a
record and Ill fill the form and Ill update in the form and Ill say update.
And I want all these updates to be reflected in my database.
Ill double click on this update button. First of all I need to search the record. So,
how do I search the record?
OrganizationEntities OE = new OrganizationEntities();
tbl_Dept d = OE.tbl_Dept.ToList().Where(x => x.Did ==
int.Parse(txtDid.Text.ToString())).FirstOrDefault();
This is how we search the record in our previous chapter. Ill simply copy that and
paste in Update button click event
protected void btnUpdate_Click(object sender, EventArgs e)
{
OrganizationEntities OE = new OrganizationEntities();
tbl_Dept d = OE.tbl_Dept.ToList().Where(x => x.Did ==
int.Parse(txtDid.Text.ToString())).FirstOrDefault ();
//Now I got the record d that I want to update
d.Dname = txtDName.Text;
d.HOD = txtHOD.Text;
d.Gender = rblGender.SelectedValue;
d.Active = ckbActive.Checked;
//After assigning the values I need to say
OE.SaveChanges();
GetAllDept();
}
Execute this, Look for 101 click search and I got the record
www.ManzoorTheTrainer.com
37
I want to update HOD name from Peter to Lilly and Gender from Male to Female and
I want to de-activate as of now and Ill say Update.
So record got updated but, has not got reflected in the grid.
I need to reload the page to get this reflection.
www.ManzoorTheTrainer.com
38
grdDept.DataBind();
This is the code that Ive in page load. I want to repeat this whenever I update or
save the record and this code I want to execute it initially for the first page load.
Go for above lines of code for refactoring. Right click Refactor Extract Method
say GetAllDept
And I can call this method wherever I want to reload the grid.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetAllDept();
}
}
private void GetAllDept()
{
OrganizationEntities OE = new OrganizationEntities();
grdDept.DataSource = OE.tbl_Dept.ToList();
grdDept.DataBind();
}
Once I say Save Ill call this GetAllDept() method and when update call GetAllDept()
method.
Thats It Execute this. This should work as expected. So first of all Ill insert a new
record. Ill say department Testing HOD bob, Male, IsActive true. Ill say save.
www.ManzoorTheTrainer.com
www.ManzoorTheTrainer.com
39
40
In this chapter Im going to show how to perform delete operation. That is Ill search
the record as usual and then Ill click on the delete button.
Once, I click the delete button that record should get deleted from the database.
Again, it is simple and the same way. Ill double click on the delete button.
protec ted void btnDelete_Click(object sender, EventArgs e)
{
//Ill search the record as usual
OrganizationEntities OE = new OrganizationEntities();
tbl_Dept d = OE.tbl_Dept.ToList().Where(x => x.Did == int.Parse(txtDid.Text.ToString())).First();
// Once I get the record Ill say
OE.DeleteObject(d);
OE.SaveChanges();
GetAllDept();
}
www.ManzoorTheTrainer.com
www.ManzoorTheTrainer.com
41
Click save.
www.ManzoorTheTrainer.com
42
www.ManzoorTheTrainer.com
43
44
In this chapter Im going to show you how to work with stored procedures. Normally,
we have 3 types of stored procedures
1) A stored procedure with no input parameters and no output parameters
Ive a stored procedure. Name is sp_GetAllEmployee where Im trying to get the
information of all the employees joining it with tbl_Dept table.
www.ManzoorTheTrainer.com
45
Now, let us see the stored procedure that does not take any input and any output
parameter.
Im going to work with first stored procedure that is sp_GetAllEmployee. For that Ive
a page called as Emp.aspx and Ill take a normal gridview where I want to display
the result of the stored procedure
www.ManzoorTheTrainer.com
46
Click finish.
Now, Ive one more window that is specifically for this model and that window is
called as Model Browser.
www.ManzoorTheTrainer.com
47
classes. You can say first one as your storage schema and the second one as your
conceptual schema.
Now, Ill explore stored procedures. So, you can see the stored procedure that Ive
added. Ill double click stored procedure.
I get a window called as Add Function Import. Now, I should click on Get Column
Information
www.ManzoorTheTrainer.com
48
These are the columns that my stored procedure is returning Eid, EName, ESal,
EDOB, Dname and HOD.
That means it is going to create an equivalent property class for this stored
procedure with all these fields as properties.
Click on Create New Complex Type and youll see the new complex type in your
model.
www.ManzoorTheTrainer.com
49
www.ManzoorTheTrainer.com
50
Ill explore the complex type. You should see all the columns as properties.
This is how we need to add the stored procedure. Add the stored procedure,
create a complex type for that and save this.
Now, Ill go back to the Employee page and in page load I want to execute that.
Ill say using OrganizationModel;
So, this is the namespace that I need to create OrganizationEntity object.
OrganizationEntities OE = new OrganizationEntities();
After creating the object the things are very simple. You need to simply call that
stored procedure as a method and it is going to return me the list of
SP_GetAllEmployee_Result the complex type that we created. So, Convert it to
ToList() and assign to the gridview.
OrganizationEntities OE = new OrganizationEntities();
GridView1.DataSource = OE.SP_GetAllEmployee().ToList();
GridView1.DataBind();
Ill save this and Im going to execute this. It should give me the information of all
the employees along with their department information.
www.ManzoorTheTrainer.com
51
So, thats it this is very simple. This is how you can call the stored procedure. Now,
In our next chapter well see how to call a stored procedure with input parameter.
www.ManzoorTheTrainer.com
52
In this chapter Im going to show you how to call a stored procedure with input
parameter but no output parameter. Ive a stored procedure called
SP_GetEmployeesByDid.
I have the employees belonging to two departments as of now (100 and 101).
Now, how do I add this stored procedure, the same process simply, right click in
OrganizationModel.edmx
www.ManzoorTheTrainer.com
53
And say update model from database. Ill go for the stored procedures and I ll select
SP_GetEmployeesByDid and Ill say finish.
www.ManzoorTheTrainer.com
54
This is what the information. Then Ill say create new complex type.
Now, it has created a type called as SP_GetEmployeesByDid_Result. So, Ill say OK.
The process of adding a stored procedure is also called as adding function import.
We are importing a function. If I explore this complex type, we should see one more
type that is nothing but your SP_GetEmployeesByDid_Result.
Instead of creating a separate complex type we can also go with the option Entities
and select tbl_Emp.
As this stored procedure is returning the columns exactly same as the columns of
tbl_Emp table.
www.ManzoorTheTrainer.com
55
Ill save this. Now, I got another function SP_GetEmployeesByDid and it is going to
return me the collection or list of SP_GetEmployeesByDid_Result (complex type).
Save this and execute. I should get the result of Employees belonging to Department
100.
www.ManzoorTheTrainer.com
56
This is very simple. If I want to get the information about the employees who belong
to department 101, I need to pass the parameter as 101.
OrganizationEntities OE = new OrganizationEntities();
GridView1.DataSource = OE.SP_GetEmployeesByDid(101).ToList();
GridView1.DataBind();
In our next chapter we will see how to call the stored procedure with input as well as
output parameters and how to read the output result into the variables (output
parameters).
www.ManzoorTheTrainer.com
57
In this chapter Im going to show you how to work with stored procedure with input
as well as output parameters.
As we know that this stored procedure is not at all going to return set of records. It
is going to return two single different values.
www.ManzoorTheTrainer.com
Go for Model browser explore the stored procedures and you should see
58
www.ManzoorTheTrainer.com
59
Now, if you observe say Get Column Information I should not get any information
because this stored procedure is not going to return any row. It is going to return
two different values for this Ill just say OK. Save this. Now, how do I call the stored
procedure the process is same.
Here I should pass one input and two output parameter variables.
Output parameter should be of type object parameter that is the class called as
object parameter. Object parameter is present in the namespace
System.Data.Objects; Ive added this namespace. using System.Data.Objects;
First output parameter with name and type. This EName should match the output
parameter @EName in stored procedure.
Second output parameter with name and type. This ESal should match the output
parameter @ESal in stored procedure. ESal is of type double and you can say the
type as Int64.
www.ManzoorTheTrainer.com
60
Pass eName and eSal object parameters. Output parameters values will be set to
eName and eSal.
OE.SP_GetEmpNameAndSalaryByEid(4, eName, eSal);
This is how you can work with stored procedure with input as well as output
parameters
Note: In Entity Framework 5.x you need to perform extra step i.e., Add Funtion Import after adding stored
procedure to your model.
www.ManzoorTheTrainer.com
61
In this chapter Im going to show you the difference between Immediate mode query
execution and deferred mode query execution.
var result = OE.tbl_Emp; //All the employees from tbl_Emp table in the result
And Im iterating through all the elements of result variable and Im trying to display
Employee Name and Employee Salary. Each and every element Im taking in item
and Ill say item.EName and item.ESal
foreach (var item in result)
{
Response.Write("Emp Name:" + item.EName + "Emp Sal:" + item.ESal + "<br>");
}
www.ManzoorTheTrainer.com
62
Save this. Ill execute this. Even then Im getting the same result. So, what is t he
difference between var result = OE.tbl_Emp; and var result = OE.tbl_Emp.ToList();
The difference is ToList() executes the query and gives the result to result variable.
Whereas the earlier case OE.tbl_Emp; with no ToList() Itll prepare the query and
query gets executed at the time of iteration.
Right click on result variable and say Add watch. Say F11. Now, you can see in watch
window
www.ManzoorTheTrainer.com
63
Here it says count that means query got executed and I got 10 records. Because,
this is an immediate mode.
I can force the Entity Framework to execute the query on Immediate mode with the
help of ToList() method. I can say .Count() or .ToArrayList().
Anything If I call any method it becomes an immediate mode. Now, Ill stop and Ill
repeat the same thing without ToList() and execute. Say F11.
Now, if you look into the watch window it says result view.
Expanding the result will Enumerate the IEnumerable. It means that the query has
not got executed yet, when it is iterating through the loop the query will be
executed.
Query gets executed whenever we iterate through the loop. Now, depending upon
the situation you proceed with either Immediate or Deferred mode execution.
Note: We will try to explore this in depth once we deal with lazyloading concept .
www.ManzoorTheTrainer.com
64
I assume that you are aware of what are transactions. Weve seen what are
transactions and the implementation of Transactions in ADO.NET.
You can go through these. The transactions in ADO.NET will explain you what a
transaction is and the later one will explain the implementation of transaction.
Now, I hope that you might have gone through these videos and you have an
understanding of transaction. Let us see the implementation of transaction in Entity
Framework.
This is not what I had in ADO.NET. My requirement is Ive department and employee
tables.
I want to create a department and at the same time I want to create an employee
belonging to that particular department
www.ManzoorTheTrainer.com
65
So, First of all let us see how to create a department. We create a department with
the help of tbl_Dept entity
OrganizationEntities OE = new OrganizationEntities();
tbl_Dept d = new tbl_Dept();
d.Dname = "PDG";
d.HOD = "Jill";
d.Gender = "M";
d.Active = true;
OE.AddTotbl_Dept(d);
OE.SaveChanges();
In the same way I want to create one more object of tbl_Emp entity.
tbl_Emp emp = new tbl_Emp();
emp.EName = "Fari";
emp.ESal = 5365353536567000;
emp.EGen = "M";
emp.EDOB = new DateTime(1984, 11, 06);
//The department id should be the id that is generated from above tbl_Dept d object.
// We know that Did is an auto generated column.
//Will the d.Did bring the Did that is inserted?
emp.Did = d.Did;
www.ManzoorTheTrainer.com
66
Ill save this and execute. As we know that the transaction is something if the above
two executions are successful I say that transaction is success.
If the first execution is successful and the second one fails it should rollback. That
means it should undo the first one also.
Ill save this and execute. Now, let me go back to the database. Let me see whether
I got the department PDG
In employee table
www.ManzoorTheTrainer.com
67
I got Fari and I got the equivalent Did that means you Entity Framework is handling
the auto increment column automatically. Because, In your OrganizationModel.edmx
you said the Did is auto generated column.
If we want all these statements to run all of them under a single transaction.
www.ManzoorTheTrainer.com
Ill say OK. Now, I get the reference to that DLL. Now Ill say
using System.Transactions;
www.ManzoorTheTrainer.com
68
69
emp.Did = d.Did;
OE.AddTotbl_Emp(emp);
OE.SaveChanges();
s.Complete();
}
Once we say s.Complete() it is going to commit the transaction. If your control does
not execute s.Complete() It means that the transaction is incomplete and it will
rollback any operation that it has performed on Entity Data Model.
Now, I get the department PDG and I get Fari belonging to department 110
www.ManzoorTheTrainer.com
70
This is very simple. Just you need to put your code inside TransactionScope and at
the end you need to call s.Complete() method.
If at all there is any exception in department execution it is not going to call the
employee execution and it is going to rollback the transaction.
Now, Ill comment out s.Complete() that means if this method is not executed it is
going to rollback all these operations and
I should not have any PDG and Fari in my database. Ill execute and look into the
database.
www.ManzoorTheTrainer.com
71
That means it has rolled back both the operations even though we say
OE.SaveChanges().
If we say s.Complete() it should commit both the operations and I should have both
the records. Ill look into the database. I get PDG department.
www.ManzoorTheTrainer.com
72
So, this is all about the transactions in your Entity Framework which is very simple.
Just create the object of TransactionScope and put all your queries or all your
operations one after the other and finally call s.Complete().
www.ManzoorTheTrainer.com
73
Hello everyone, in this chapter Im going to show you what are navigation properties.
Now, say Ive a textbox and a button and I want to search the employee based on
the department name that is Im going to insert department name here and I say
search.
What is that it should do, it should get me all the employees belonging to the
department entered.
So, what is our normal logic we take the department name and we try to find out
department id.
Now, lets see tbl_Dept and tbl_Emp tables. From tbl_Dept table I get DName
(Department Name). From DName Ill try to find out Did.
With that Did Ill write a query on tbl_Emp table to get the information.
www.ManzoorTheTrainer.com
74
Normal procedure
protected void btnSearch_Click(object sender, EventArgs e)
{
OrganizationEntities OE = new OrganizationEntities();
int did = OE.tbl_Dept.ToList().Where(x => x.Dname ==
txtDeptName.Text).FirstOrDefault().Did;
var emps = OE.tbl_Emp.ToList().Where(x => x.Did == did);
//By using where clause Ill get all the employees belonging to that particular
department
grdEmps.DataSource = emps;
grdEmps.DataBind();
}
Let us achieve the same thing with the help of Navigation properties. Let us see how
simple it is.
www.ManzoorTheTrainer.com
75
In this OrganizationModel tbl_Dept have a navigation property tbl_Emp. Ill use this
property.
It is going to find the department and extract all the employees of the department
and store it in emps.
protected void btnSearch_Click(object sender, EventArgs e)
{
OrganizationEntities OE = new OrganizationEntities();
var emps = OE.tbl_Dept.ToList().Where(x => x.Dname ==
txtDeptName.Text).FirstOrDefault().tbl_Emp;
grdEmps.DataSource = emps;
grdEmps.DataBind();
}
Save this and execute. Ill search for QA and Ill get the same result.
Instead of writing two queries in the normal procedure we can simplify it with
Navigation properties.
In the same way you can navigate from the employee table to the department table.
www.ManzoorTheTrainer.com
76
In this chapter Im going to show you what lazy loading is and also demonstrate the
topic that we already learned that is immediate mode and deferred mode as these
two things make developer confused.
So, lets say Ive a gridview and I want to display all the departments at page load.
Execute it. Now, if you look at a window on the right that is IntelliTrace.
This is the new window we got in VS 2010 which is used to examine our query and
flow.
www.ManzoorTheTrainer.com
77
Now, at the time of assigning the result to the gridview, It shoud execute a select
query.
www.ManzoorTheTrainer.com
78
This query got executed at the time of databinding to the gridview. Say F5.
Now, Im using this result one more time. If you observe in IntelliTrace you got one
more ExecuteReader.
www.ManzoorTheTrainer.com
79
In our earlier code it is hitting the database two times whereas here itll hit the
database only once.
I get select query there and it is not at all going to hit the database at the time of
binding, neither at the time of iterations
www.ManzoorTheTrainer.com
www.ManzoorTheTrainer.com
80
81
What I want is if I say search it should get all the employees whose department type
is InActive (QA & Admin).
If I check Active and if I say search I should get all the employees whose department
is Active (Development, Testing and PDG).
Im going to implement this, in this youll see what lazy loading is and we are going
to make use of IntelliTrace window we saw just now. And that window is available
only when we go for debugging mode.
Let us see.
protected void Button1_Click(object sender, EventArgs e)
{
OrganizationEntities OE = new OrganizationEntities();
var result = OE.tbl_Dept.Where(x => x.Active == ckbActive.Checked).ToList();
foreach (var d in result)
{
Response.Write(d.Dname + "<br/>");
}
}
Save and execute.
www.ManzoorTheTrainer.com
82
Now, what I want is I want all the employees belonging to the particular department
protected void Button1_Click(object sender, EventArgs e)
{
OrganizationEntities OE = new OrganizationEntities();
var result = OE.tbl_Dept.Where(x => x.Active == ckbActive.Checked).ToList();
www.ManzoorTheTrainer.com
83
Now, Ill put a breakpoint and let me see how many hits it is making to the database.
www.ManzoorTheTrainer.com
84
Definitely it is going to execute reader that is it is going to hit the database to get all
the departments where active is whatever u checked or unchecked from the
checkbox.
It has executed another select query that means to get all the employees of that
department it is executing a query with where clause. That is the second hit to the
database. Till now weve two hits.
www.ManzoorTheTrainer.com
85
Now, another department it is going to hit the database third time. For each and
every department.
It is going to take Did and write query on department table, hit the database and get
data for that.
this.ContextOptions.LazyLoadingEnabled = true;
www.ManzoorTheTrainer.com
86
Im getting only department names. Im not at all getting any employees in that
department.
Now, Ill put the breakpoint and lets check the execution once again.
www.ManzoorTheTrainer.com
87
Earlier it was hitting the database at this point. But, here there is no query.
www.ManzoorTheTrainer.com
88
So, if you observe this it is not at all hitting database that is when we are iterating
through Employee table.
Say, if I have 100 departments. It is going to get all 100 departments and for each
department it is going to hit the database and get all the records of that particular
department. That means it is going to hit the database 100 times for each
department to get employees and one time to get all the departments.
But, without LazyLoadingEnabled itll hit database only once and we are not getting
the employees.
That is after getting all the records from the department I should use Include as
shown.
protected void Button1_Click(object sender, EventArgs e)
{
OrganizationEntities OE = new OrganizationEntities();
var result = OE.tbl_Dept.Include("tbl_Emp").Where(x => x.Active ==
ckbActive.Checked).ToList();
Let us see the query that is going to prepare at the Include line of code.
www.ManzoorTheTrainer.com
89
Earlier it is hitting the database at for each loop. Now, there is no hit to the database
and it is also getting all the employees.
Say F5. Ill get the same information but with single hit to the database this time.
www.ManzoorTheTrainer.com
90
If you make LazyLoadingEnabled to false Itll make single hit to the database with
a single query. (Eager Loading)
It all depends on your analysis to go either with LazyLoadingEnable to true or fal se.
www.ManzoorTheTrainer.com
91
In this chapter Im going to show you a magic. Yes, the new feature ASP.NET
dynamic Entity data website. You wont believe that this can create a website in 5
easy steps if you have your database ready with all CURD operations. Say, Ive my
database with me tbl_Dept and tbl_Emp.
Now, I want to create a web application which perform the operations like insert,
update, delete and select all on these tables.
What is that I need to do, I need to simply start a project or a website that is
nothing but ASP.NET Dynamic Data Entities Website and Ill name it as
MicrosoftMagicWebApp.
www.ManzoorTheTrainer.com
92
I need not to worry about those as of now. As I told you that there are 5 steps that
you need to perform.
www.ManzoorTheTrainer.com
93
1) Adding Entity Data Model. (The thing that we did in our earlier articles)
2) Adding the namespace
3) Uncomment single Line of code in Global.asax
4) Change YourDataContextType to your context class
5) Set ScaffoldAllTables=true
1) Adding Entity Data Model. (The thing that we did in our earlier articles)
Right click on the project and Say add new item. Im going to add ADO.NET Entity
Data Model.
www.ManzoorTheTrainer.com
Say Next.
www.ManzoorTheTrainer.com
94
Click Next.
www.ManzoorTheTrainer.com
95
www.ManzoorTheTrainer.com
96
97
Copy this namespace and add this namespace in the Global.asax file
using MicrosoftMagicWebApp;
3) Uncomment single Line of code in Global.asax
www.ManzoorTheTrainer.com
98
4) And in place of YourDataContextType write your context class that is nothing but
your OrganizationEntities
5) Set ScaffoldAllTables=true
www.ManzoorTheTrainer.com
99
Thats it we are ready with our web application. Im going to execute this. As weve
taken two tables in the Entity Data Model.
The two tables are listed here in a beautiful grid. If I click tbl_Dept.
I can perform all the CRUD operations that is I can insert a new department with this
beautiful form
www.ManzoorTheTrainer.com
100
I can delete the existing department and I can go for the details of the department.
www.ManzoorTheTrainer.com
101
And the beautiful thing is that there is a field or column called as tbl_Emp. Click on
View tbl_Emp.
Go back to home
www.ManzoorTheTrainer.com
102
I get all the employees of that particular department. Ive wonderful dropdownlist
which lists all the departments.
So, your Microsoft, your Visual Studio and your dynamic data site identifies that the
tbl_Emp have a foreign key tbl_Dept. So, it makes a dropdownlist for department.
www.ManzoorTheTrainer.com
103
Ill get all the employees information with excellent paging feature. If we have 100
tables in our Entity Data Model.
Well find all the 100 tables list in the home page and all the forms associated with
each table.
You can modify or customize this and you can use it as you like.
www.ManzoorTheTrainer.com
For your own Unlimited Reading and FREE eBooks today, visit:
http://www.Free-eBooks.net
Share this eBook with anyone and everyone automatically by selecting any of the
options below:
COPYRIGHT INFORMATION
Free-eBooks.net respects the intellectual property of others. When a book's copyright owner submits their work to Free-eBooks.net, they are granting us permission to distribute such material. Unless
otherwise stated in this book, this permission is not passed onto others. As such, redistributing this book without the copyright owner's permission can constitute copyright infringement. If you
believe that your work has been used in a manner that constitutes copyright infringement, please follow our Notice and Procedure for Making Claims of Copyright Infringement as seen in our Terms
of Service here:
http://www.free-ebooks.net/tos.html