Sei sulla pagina 1di 106

Entity Framework - Simplified

This is the first edition : 2013.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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

Entity Framework - Simplified

About the Author


ManzoorTheTrainer MCTS, MCPD and MCT.
Planning for Ph.D in the domain of Middleware
Technologies with over 14+ years of teaching and
over 8+ years of Development Exp. Has an excellent
track record as one of the best IT faculty in
imparting technology. Makvin's Ace Trainer who
believes in giving the real essence of technology to
the learner this uniqueness has made me earn a
strong foothold in the IT Training Industry.
Microsoft Certified Professional Profile (MCP)
Founder of ManzoorTheTrainer

www.ManzoorTheTrainer.com

Entity Framework - Simplified

About the Technical Reviewers And Supporters:


I am really thankful to Almighty and all the followers of my video training portal
www.ManzoorTheTrainer.com and encouraging me to take an step of writing a technical
book on the latest data access technology i.e., Entity Framework. I am also thankful to Mr.
Satish Kumar Mandava, my colleague having 6+ yrs of .NET expertise for reviewing this
book and giving feedbacks for betterment.
I am also thankful to my organization Efficacy System and my PM Mr.Srikanth (PMP)
for motivating me always.
Extending my special thanks to Mr. Shivprasad Koirala Sir for encouraging and
guiding me and to all the experts from whom I got inspired.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Chapter 1: Introduction to Entity Framework


Few Necessities Of New Data Access Technology Entity Framework:

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 layer of abstraction between your Application and Database.

Want to write C# language syntaxed queries to work with any database with full
intellisense support for columns and tables name.(Strongly Typed)

Want to make database independent apps.

Introduction To Entity Framework:

The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM)


framework that enables developers to work with relational data as domain-specific
objects, eliminating the need for most of the data access plumbing code that
developers usually need to write.

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.
-

Definition of Entity Framework given by Microsoft

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Various approaches to work with Entity Framework:

Database First (This eBook is Focused on):


o

Creating the model from database (Generating Classes or Class Diagram


from Database Tables).

Model First
o

Creating the database from model (Generating Database Tables from Classes
or Class Diagram).

Code First (Some Time POCO)


o

Coding classes against the existing Database is Code First.

Creating the database from the coded classes(No class diagrams) is POCO.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Chapter 2: Creating an Entity Data Model

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.

So, In Department table Ive Did(Department ID), Dname(Department Name), HOD


and Gender in which Did is primary key.

In Employee table Ive Eid(Employee ID), Ename(Employee Name), Esal(Employee


Salary), EGen(Employee Gender), EDOB(Employee Date Of Birth) and Did is the
foreign key from department table.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Creating Entity Data Model:

Create a web Project say EntityFrameworkPart-1

Lets create our entity data model(EDM) which is the heart of Entity Framework and it
is very simple.

Ill goto my Project what Ive created as EntityFrameworkPart-1

Right click the project

Add new item

Select ADO.NET Entity Data Model

And Ill name it as OrganizationModel.edmx

Click Add

It is going to add in App_Code folder

Ill say yes

Itll fire a window with two options for me.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

1. Generate Empty Database (Create a model from an existing database)


2. Empty Model (Create model first then create the database)

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

Entity Framework - Simplified

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.

Heres my Entity Data Model

As you might have seen, in a single department I can have n number of employees.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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 .

So, this is my Entity Data Model.

Right click on Entity Data Model

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

Entity Framework - Simplified

12

The Designer tag contains some UI related to our Entity Data Model (Graphical table
data)

The Runtime tag consists of 3 parts


1. SSDL (Storage Schema Definition Language) [Info about database, tables,
columns.. for SQL data]
<edmx:StorageModels >
<Schema Namespace="OrganizationModel.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="OrganizationModelStoreContainer">
<EntitySet Name="tbl_Dept" EntityType="OrganizationModel.Store.tbl_Dept "
store:Type="Tables"
Schema="dbo" />
<EntitySet Name="tbl_Emp" EntityType="OrganizationModel.Store.tbl_Emp " store:Type="Tables"
Schema="dbo" />
<AssociationSet Name="F K_tbl_Emp_tbl_Dept "
Association="OrganizationModel.Store.F K_tbl_Emp_tbl_Dept ">
<End Role="tbl_Dept " EntitySet="tbl_Dept" />
<End Role="tbl_Emp" EntitySet="tbl_Emp" />
</AssociationSet>
</EntityContainer>
<EntityType Name="tbl_Dept">
<Key>
<PropertyRef Name="Did" />
</Key>
<Property Name="Did" Type="int" Nullable ="false " StoreGeneratedPattern="Identity" />
<Property Name="Dname " Type="varchar" MaxLength="50" />
<Property Name="HOD" Type="varchar" Nullable="false " MaxLength="50" />
<Property Name="Gender" Type="varchar" Nullable="false " MaxLength="50" />
<Property Name="Active" Type="bit" />
</EntityType>
<EntityType Name="tbl_Emp">
<Key>
<PropertyRef Name="Eid" />
</Key>
<Property Name="Eid" Type="int" Nullable="false " StoreGeneratedPattern="Identity" />
<Property Name="EName " Type="varchar" Nullable ="false " MaxLength="50" />
<Property Name="ESal" Type="float" Nullable ="false " />
<Property Name="EGen" Type="varchar" Nullable ="false " MaxLength="10" />
<Property Name="EDOB" Type="datetime" Nullable ="false " />
<Property Name="Did" Type="int" />
</EntityType>
<Association Name="F K_tbl_Emp_tbl_Dept">
<End Role="tbl_Dept" Type="OrganizationModel.Store.tbl_Dept" Multiplicity="0..1" />
<End Role="tbl_Emp" Type="OrganizationModel.Store.tbl_Emp " Multiplicity="*" />
<ReferentialConstraint >
<Principal Role="tbl_Dept">
<PropertyRef Name="Did" />
</Principal>
<Dependent Role="tbl_Emp">
<PropertyRef Name="Did" />
</Dependent>
</ReferentialConstraint >
</Association>
<Function Name="SP_GetAllEmployee " Aggregate="false" BuiltIn="false "
NiladicFunction="false " IsComposable ="false "
ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" />
<Function Name="SP_GetEmployeesByDid" Aggregate="false" BuiltIn="false " NiladicFunction="false "
IsComposable ="false " ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo">
<Parameter Name="Did" Type="int" Mode="In" />
</Function>

www.ManzoorTheTrainer.com

Entity Framework - Simplified

13

<Function Name="SP_GetEmpNameAndSalaryByEid " Aggregate="false " BuiltIn="false "


NiladicFunction="false " IsComposable ="false "
ParameterTypeSemantics="AllowImplic itConversion" Schema="dbo">
<Parameter Name="Eid" Type="int" Mode="In" />
<Parameter Name="EName " Type="varchar" Mode="InOut" />
<Parameter Name="ESal" Type="float" Mode="InOut" />
</Function>
</Schema></edmx:StorageModels>

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

Entity Framework - Simplified

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 >

3. C-S Mapping [Column Mappings]


<edmx:Mappings >
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntityContainerMapping StorageEntityContainer="OrganizationModelStoreContainer"
CdmEntityContainer="OrganizationEntities ">
<EntitySetMapping Name="tbl_Dept "><EntityTypeMapping
TypeName="OrganizationModel.tbl_Dept"><MappingFragment StoreEntitySet="tbl_Dept">
<ScalarProperty Name="Active" ColumnName ="Active" />
<ScalarProperty Name="Did" ColumnName ="Did" />
<ScalarProperty Name="Dname" ColumnName ="Dname " />
<ScalarProperty Name="HOD" ColumnName ="HOD" />
<ScalarProperty Name="Gender" ColumnName ="Gender" />
</MappingFragment ></EntityTypeMapping></EntitySetMapping>
<EntitySetMapping Name="tbl_Emp"><EntityTypeMapping
TypeName="OrganizationModel.tbl_Emp"><MappingFragment StoreEntitySet="tbl_Emp">
<ScalarProperty Name="Eid" ColumnName ="Eid" />
<ScalarProperty Name="EName " ColumnName ="EName " />
<ScalarProperty Name="ESal" ColumnName ="ESal" />
<ScalarProperty Name="EGen" ColumnName ="EGen" />
<ScalarProperty Name="EDOB" ColumnName ="EDOB" />
<ScalarProperty Name="Did" ColumnName ="Did" />
</MappingFragment ></EntityTypeMapping></EntitySetMapping>
<FunctionImportMapping FunctionImportName ="SP_GetAllEmployee"
FunctionName="OrganizationModel.Store.SP_GetAllEmployee ">
<ResultMapping>
<ComplexTypeMapping TypeName="OrganizationModel.SP_GetAllEmployee_Result ">
<ScalarProperty Name="Eid" ColumnName ="Eid" />
<ScalarProperty Name="EName " ColumnName ="EName " />
<ScalarProperty Name="Esal" ColumnName ="Esal" />
<ScalarProperty Name="EDOB" ColumnName ="EDOB" />

www.ManzoorTheTrainer.com

Entity Framework - Simplified

15

<ScalarProperty Name="Dname" ColumnName ="Dname" />


<ScalarProperty Name="HOD" ColumnName ="HOD" />
</ComplexTypeMapping>
</ResultMapping>
</FunctionImportMapping>
<FunctionImportMapping FunctionImportName ="SP_GetEmployeesByDid"
FunctionName="OrganizationModel.Store.SP_GetEmployeesByDid ">
<ResultMapping>
<ComplexTypeMapping TypeName="OrganizationModel.SP_GetEmployeesByDid_Result ">
<ScalarProperty Name="Eid" ColumnName ="Eid" />
<ScalarProperty Name="EName " ColumnName ="EName " />
<ScalarProperty Name="ESal" ColumnName ="ESal" />
<ScalarProperty Name="EGen" ColumnName ="EGen" />
<ScalarProperty Name="EDOB" ColumnName ="EDOB" />
<ScalarProperty Name="Did" ColumnName ="Did" />
</ComplexTypeMapping>
</ResultMapping>
</FunctionImportMapping>
<FunctionImportMapping FunctionImportName ="SP_GetEmpNameAndSalaryByEid "
FunctionName="OrganizationModel.Store.SP_GetEmpNameAndSalaryByEid " />
</EntityContainerMapping>
</Mapping>
</edmx:Mappings >

CLR generates 3 different files for Runtime tag at runtime.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

16

Chapter 3: Exploring Entity Data Model

In this chapter we are going to explore the class that gets generated whenever we
create Entity Data Model

The class is OrganizationModel.Designer.cs and Ill double click this file.

Now, there are two important things that you need to remember from this file

www.ManzoorTheTrainer.com

Entity Framework - Simplified

17

1. Namespace (You got namespace as OrganizationModel)


namespace OrganizationModel {}
o
o
o

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.

2. The Object contexts that we have that is OrganizationEntities

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

Entity Framework - Simplified

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

Entity Framework - Simplified

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.

public global::System.Int32 Did


{
get
{
return _Did;
}
set
{
if (_Did != value)
{
OnDidChanging(value);
ReportPropertyChanging( "Did");
_Did = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Did");
OnDidChanged();
}
}
}

www.ManzoorTheTrainer.com

Entity Framework - Simplified

20

public global::System.String Dname


{
get
{
return _Dname;
}
set
{
OnDnameChanging(value);
ReportPropertyChanging( "Dname");
_Dname = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged( "Dname");
OnDnameChanged();
}
}
public global::System.String HOD
{
get
{
return _HOD;
}
set
{
OnHODChanging(value);
ReportPropertyChanging( "HOD");
_HOD = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged( "HOD");
OnHODChanged();
}
}

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.

public EntityCollection<tbl_Emp> tbl_Emp

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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);
}
}
}

public global::System.Int32 Eid


{
get
{
return _Eid;
}
set
{
if (_Eid != value)
{
OnEidChanging(value);
ReportPropertyChanging( "Eid");
_Eid = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Eid");
OnEidChanged();
}
}
}
public global::System.String EName
{
get
{
return _EName;
}
set
{
OnENameChanging(value);
ReportPropertyChanging( "EName");
_EName = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged( "EName");
OnENameChanged();
}
}

public global::System.Double ESal


{
get
{
return _ESal;
}
set
{

www.ManzoorTheTrainer.com

Entity Framework - Simplified


OnESalChanging(value);
ReportPropertyChanging( "ESal");
_ESal = StructuralObject.SetValidValue(value);
ReportPropertyChanged( "ESal");
OnESalChanged();
}
}

public global::System.String EGen


{
get
{
return _EGen;
}
set
{
OnEGenChanging(value);
ReportPropertyChanging( "EGen");
_EGen = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged( "EGen");
OnEGenChanged();
}
}

public global::System.DateTime EDOB


{
get
{
return _EDOB;
}
set
{
OnEDOBChanging(value);
ReportPropertyChanging( "EDOB");
_EDOB = StructuralObject.SetValidValue(value);
ReportPropertyChanged( "EDOB");
OnEDOBChanged();
}
}

public Nullable<global::System.Int32> Did


{
get
{
return _Did;
}
set
{
OnDidChanging(value);
ReportPropertyChanging( "Did");
_Did = StructuralObject.SetValidValue(value);
ReportPropertyChanged( "Did");
OnDidChanged();
}
}

www.ManzoorTheTrainer.com

22

Entity Framework - Simplified

23

public EntityReference<tbl_Dept > tbl_DeptReference


{
get
{
return
((IEntityWithRelationships)this).RelationshipManager.Get RelatedReference<tbl_Dept >("
OrganizationModel.FK_tbl_Emp_tbl_Dept", "tbl_Dept");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedRefer
ence<tbl_Dept>("OrganizationModel.F K_tbl_Emp_tbl_Dept ", "tbl_Dept",
value);
}
}
}

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

public void AddTotbl_Dept(tbl_Dept tbl_Dept)


{
base.AddObject("tbl_Dept", tbl_Dept);
}

public void AddTotbl_Emp(tbl_Emp tbl_Emp)


{
base.AddObject("tbl_Emp", tbl_Emp);
}
public partial class OrganizationEntities : ObjectContext

Now, one important thing is OrganizationEntities class is partial because there


are many cases where you need to edit this class that means before insertion,
before adding this to the database, I want to perform some business operations
or business validations.
I can go and write the code here itself. But, the problem is that whenever I
refresh my OrganizationModel or if I add some new tables to this model or if I
update the model if I perform anything on the model it is going to regenerate this
file means itll override all our code.
So, in those scenarios what is that we can do is we can have a separate class
which is again a partial class and you can add your customized code there.
So, that whenever you update Entity Data Model you code should not get
overridden.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

24

Chapter 4: Exploring Entity Data Model in EF 5.X

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

Entity Framework - Simplified

25

Simply delete those files.

Now, you can rebuild the project and youll see that everything is successful.

Go for OrganizationDBEntities1 file.

And youll find all the things as usual.

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

Entity Framework - Simplified

26

Chapter 5 : Performing an Insert Operation

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.

As we know that department id is auto generated column we do not require a field


for it on the form.

<table cellpadding="0" cellspacing="0" class="style1">


<tr>
<td style="text-align: right">
Dept ID</td>
<td>
<asp:TextBox ID="txt Did" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="text-align: right">
&nbsp;</td>
<td>
<asp:Button ID="btnSearch" runat="server" onclick="btnSearch_Click"
Text="Search" />
</td>
</tr>
<tr>
<td style="text-align: right">
Dept Name</td>
<td>
<asp:TextBox ID="txt DName" runat="server"></asp:TextBox>
</td>

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

Ill double click the save button and write code.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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

Entity Framework - Simplified

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

Currently weve 2 departments that is QA and Admin. Im going to add a department


called as development.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

30

Ill say department name as Development, HOD as Long, Gender as male and Ill say
IsActive. Save this.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

31

Chapter 6 : Performing a Select Operation

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.

OrganizationEntities OE = new OrganizationEntities(); I

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.

So, the name of the property is tbl_Dept. which is available in OrganizationEntities.


No need to worry about these much as of now.
public ObjectSet<tbl_Dept> tbl_Dept
{
get
{
if ((_tbl_Dept == null))
{
_tbl_Dept = base.CreateObjectSet<tbl_Dept>("tbl_Dept");
}
return _tbl_Dept;

www.ManzoorTheTrainer.com

Entity Framework - Simplified


}
}

Ill say

grdDept.DataSource = OE.tbl_Dept.ToList();
grdDept.DataBind();

Ill get all the departments.


using OrganizationModel;
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();
}

If I want to display all the employees again that is very simple Ill say
grdDept.DataSource = OE.tbl_Emp.ToList();

It should display all the employees in the gridview.

www.ManzoorTheTrainer.com

32

Entity Framework - Simplified

www.ManzoorTheTrainer.com

33

Entity Framework - Simplified

34

Chapter 7 : Performing a Search Operation

In this chapter Im going to show you how to perform search operation.

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

OrganizationEntities OE = new OrganizationEntities();

tbl_Dept d = OE.tbl_Dept.ToList().Where(x => x.Did == int.Parse(txtDid.Text.ToString())).First OrDefault();

In our previous chapter we saw how to get list of departments.


You can take any variable for x. Single line of code will perform a where clause.
Now, you need not to worry about what is this. x => x is a lambda expression.
In our next release we will see how to write all lambda expressions.
Now, I got the result in d. Now, I can fill the form that is nothing but
protected void btnSearch_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())).First OrDefault();
txtDName.Text = d.Dname;
txtHOD.Text = d.HOD;

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

I got QA, jack, Male and IsActive is false.

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

Entity Framework - Simplified

36

Chapter 8 : Performing an Update Operation

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

Entity Framework - Simplified

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.

So, what is that I can do it is very simple.

OrganizationEntities OE = new OrganizationEntities();


grdDept.DataSource = OE.tbl_Dept.ToList();

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

I get the record here that is Testing Bob.


It should get reflected right away here. It got updated.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

So this is how you can perform search and update operations.


In our next chapter well see how to perform a delete operation.

www.ManzoorTheTrainer.com

39

Entity Framework - Simplified

40

Chapter 9 : Performing a Delete Operation

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();
}

Ill look for the department 103

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Ill perform a delete operation

So 103 got deleted. Ill re-insert this department

www.ManzoorTheTrainer.com

41

Entity Framework - Simplified

Click save.

I got the department. Now, the department ID is 104.


Ill again look for 104, Search and Ill perform a delete operation.

www.ManzoorTheTrainer.com

42

Entity Framework - Simplified

So, this is all about your delete operation.

www.ManzoorTheTrainer.com

43

Entity Framework - Simplified

44

Chapter 10 : Working With Stored Procedures-I

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.

2) A stored procedure with input parameters and no output parameters


This stored procedure is a procedure where Ive input parameter that is department
ID.Im trying to get the information of all the employees belonging to a specific
department

3) A stored procedure with input parameters and output parameters


This stored procedure is a procedure where Ive input parameter that is Employee
ID.

Im trying to get the information, that is employee name and salary

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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

Now, I need to add sp_GetAllEmployee to my EntityDataModel. To do so, Ill double


click on EntityDataModel (OrganizationModel.edmx). Right click and Ill say update
model from database

Explore stored procedures and Im going to take sp_GetAllEmployee

www.ManzoorTheTrainer.com

Entity Framework - Simplified

46

Click finish.
Now, Ive one more window that is specifically for this model and that window is
called as Model Browser.

If I explore this Model Browser, Ive Model.Store in OrganizationModel. This store is


nothing but direct relation to your database and the model is nothing but your

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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

Entity Framework - Simplified

48

These are the columns that my stored procedure is returning Eid, EName, ESal,
EDOB, Dname and HOD.

Now, I'll say Create New Complex Type.

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

Entity Framework - Simplified

49

New complex type name is SP_GetAllEmployee_Result. Click OK.

So, I get a function import that is SP_GetAllEmployee and an associated complex


type that is SP_GetAllEmployee_Result.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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

Entity Framework - Simplified

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

Entity Framework - Simplified

52

Chapter 11 : Working With Stored Procedures-II

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.

Ill be passing DepartmentID(Did) as input parameter and I should get the


employees belonging to that particular department. Ill just right click on the
employee table and say show table data.

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

Entity Framework - Simplified

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

Entity Framework - Simplified

54

Save OrganizationModel.edmx. Go back to your model browser explore stored


procedures folder from storage model

Double click on the SP_GetEmployeesByDid and say get column information.

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

Entity Framework - Simplified

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).

Now, Im going to call this method or stored procedure (SP_GetEmployeesByDid).


The process is same simply I need to say instead of GetAllEmployees
OrganizationEntities OE = new OrganizationEntities();
GridView1.DataSource = OE.SP_GetEmployeesByDid(100).ToList();
GridView1.DataBind();

Save this and execute. I should get the result of Employees belonging to Department
100.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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();

This is all about calling a stored procedure with input parameter.

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

Entity Framework - Simplified

57

Chapter 12 : Working With Stored Procedures-III

In this chapter Im going to show you how to work with stored procedure with input
as well as output parameters.

Ive a stored procedure SP_GetEmpNameAndSalaryByEid in which Eid is the input


parameter that means Im going to pass Eid and

Im expecting employee name in a parameter called as @EName and Employee


salary in the parameter called as @ESal. So, @Ename and @ESal are output
parameters. Let us see how to call this stored procedure.

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.

I need to do the same process.

Right click in OrganizationModel.edmx Update model from database. Add that


particular stored procedure (SP_GetEmpNameAndSalaryByEid).

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Click finish and save.

Go for Model browser explore the stored procedures and you should see

58

SP_GetEmpNameAndSalaryByEid the new stored procedure that we have added.


Double click this

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

ObjectParameter eName=new ObjectParameter("EName",typeof(System.String));

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.

ObjectParameter eSal=new ObjectParameter("ESal",typeof(System.Int64));

www.ManzoorTheTrainer.com

Entity Framework - Simplified

60

OrganizationEntities OE = new OrganizationEntities();

Pass eName and eSal object parameters. Output parameters values will be set to
eName and eSal.
OE.SP_GetEmpNameAndSalaryByEid(4, eName, eSal);

For displaying these output parameters.


Response.Write("Employee Name :" + eName.Value.ToString());
Response.Write("<br/> Employee Salary :" + eSal.Value.ToString());

Save this and execute.

Lets change the parameter Eid


ObjectParameter eName=new ObjectParameter("EName",typeof(System.String));
ObjectParameter eSal=new ObjectParameter("ESal",typeof(System.Int64));
OrganizationEntities OE = new OrganizationEntities();
OE.SP_GetEmpNameAndSalaryByEid(7, eName, eSal);
Response.Write("Employee Name :" + eName.Value.ToString());
Response.Write("<br/> Employee Salary :" + eSal.Value.ToString());

You should get different values.

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

Entity Framework - Simplified

61

Chapter 13 : Immediate Mode Vs Differed Mode

In this chapter Im going to show you the difference between Immediate mode query
execution and deferred mode query execution.

So, as of now Ive OrganizationEntities object

OrganizationEntities OE = new OrganizationEntities();

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>");
}

Now, Ill execute. Here I get all the records.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

62

Now, Ill make changes to this. Ill say

var result = OE.tbl_Emp.ToList();

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.

This kind of execution is called as immediate mode.

Whereas the earlier case OE.tbl_Emp; with no ToList() Itll prepare the query and
query gets executed at the time of iteration.

So, this kind of execution is called as deferred mode.

Observe the difference let me put a breakpoint at var result = OE.tbl_Emp.ToList();

Right click on result variable and say Add watch. Say F11. Now, you can see in watch
window

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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

Entity Framework - Simplified

64

Chapter 14: Working With Transactions

In this chapter Im going to show you the implementation of Transaction in


EntityFramework.

I assume that you are aware of what are transactions. Weve seen what are
transactions and the implementation of Transactions in ADO.NET.

If you want you can go through www.manzoorthetrainer.com and in your ADO.NET


module last two videos

Transactions in ADO.NET and Implementing 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.

And, my requirement is little different here.

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

Entity Framework - Simplified

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

Entity Framework - Simplified

66

Let us see that. Now, Ill say


OE.AddTotbl_Emp(emp);
OE.SaveChanges();

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

Yes, I got the department PDG and Did is 108.

In employee table

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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 you see in properties window StoreGeneratedPattern is Identity. So, it is handling


the things automatically.

Now, what if Department is executed successfully employee insertion fails.

If department is executed Ive one statement and I say OE.SaveChanges();

If we want all these statements to run all of them under a single transaction.

To achieve that I need to implement transaction in Entity Framework.

For that I need to add a reference to a DLL called as


System.Transactions;

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Ill say OK. Now, I get the reference to that DLL. Now Ill say
using System.Transactions;

And Ill be working with TransactionScope class as shown below.

OrganizationEntities OE = new OrganizationEntities();


using (TransactionScope s = new TransactionScope())
{
tbl_Dept d = new tbl_Dept();
d.Dname = "PDG";
d.HOD = "Jill";
d.Gender = "M";
d.Active = true;
OE.AddTotbl_Dept(d);
OE.SaveChanges();
tbl_Emp emp = new tbl_Emp();
emp.EName = "Fari";
emp.ESal = 5365353536567000;
emp.EGen = "M";
emp.EDOB = new DateTime(1984, 11, 06);

www.ManzoorTheTrainer.com

68

Entity Framework - Simplified

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.

Save this and execute.

Now, I get the department PDG and I get Fari belonging to department 110

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

I have nither PDG department.

Nor Fari as an employee.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

I get Fari employee.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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().

It is going to commit the transaction.

If this method is not called it will automatically rollback.

So, this is all about transactions.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

73

Chapter 15 : Working With Navigation Properties

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.

Double click on search button. Import the namespace using OrganizationModel;

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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();
}

Save this and execute. Ill search for department QA.

Let us achieve the same thing with the help of Navigation properties. Let us see how
simple it is.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

This is the feature and the advantage of navigation properties.

In the same way you can navigate from the employee table to the department table.

So, this is all about your Navigation Properties.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

76

Chapter 16 : Lazy Loading in Entity Framework

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.

We already implemented, the code is very simple.


using OrganizationModel;
OrganizationEntities OE = new OrganizationEntities(); //place a breakpoint here
var result = OE.tbl_Dept; //Deferred mode of execution
grdDept.DataSource = result;
grdDept.DataBind();
foreach (var d in result)
{
Response.Write(d.Dname + "<br/>");
}

Execute it. Now, if you look at a window on the right that is IntelliTrace.

Click on this window.

This window I can get get it from Debug IntelliTrace.

This is the new window we got in VS 2010 which is used to examine our query and
flow.

Now, Ill say F10

www.ManzoorTheTrainer.com

Entity Framework - Simplified

77

Here Im going to create a query OE.tbl_Dept and say F10.

If youve observed in IntelliTrace you wont find any query execution.

Now, at the time of assigning the result to the gridview, It shoud execute a select
query.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

78

If you observe in the IntelliTrace we got a query that is Select Did,DName..

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.

So, this is called as your deferred mode of execution.

Making it to Immediate mode by .ToList().

www.ManzoorTheTrainer.com

Entity Framework - Simplified

79

OrganizationEntities OE = new OrganizationEntities();


var result = OE.tbl_Dept.ToList();
grdDept.DataSource = result;
grdDept.DataBind();
foreach (var d in result)
{
Response.Write(d.Dname + "<br/>");
}

We are forcing it to execute the query here itself.

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

Entity Framework - Simplified

You can see that, we have only one select query.

So, this is your immediate mode of execution.

Now, Ive all the departments listed.

www.ManzoorTheTrainer.com

80

Entity Framework - Simplified

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.

Ill check Active and search. I get Active departments.

Ill uncheck Active and search and I get InActive departments.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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();

foreach (var d in result)


{
Response.Write(d.Dname + "<br/>");
//using navigation properties that we learned
//It gives all the employees belonging to the particular department
foreach (var emp in d.tbl_Emp)
{
Response.Write(emp.EName + "<br/>");
}
}

Save this and execute. Ill say search.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

83

I get all the InActive departments and their employees.

Now, Ill put a breakpoint and let me see how many hits it is making to the database.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

The query is available here.

Let us observe at foreach point of time.

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

Entity Framework - Simplified

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.

So, what we saw is we had three hits to the database.

Now, Ill just go back to my OrganizationModel designer class.


(OrganizationModel.Designer.cs)

In the constructors section there is property LazyLoadingEnabled set to true.

this.ContextOptions.LazyLoadingEnabled = true;

Ill make it to false. Save this and Im gonna execute this.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

Let us see how many queries it is executing on the database.

Say F10. As usual the query that is executed here.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

87

Earlier it was hitting the database at this point. But, here there is no query.

Earlier by default, it is executing a select query on database Employee table with


where clause and department ID is equals to the value whatever we get the
department table.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

88

So, if you observe this it is not at all hitting database that is when we are iterating
through Employee table.

We get that feature only once weve LazyLoadingEnabled.

But the problem is that it was hitting database three times.

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.

Total 101 times hits to the database.

But, without LazyLoadingEnabled itll hit database only once and we are not getting
the employees.

So, to get both the fruits, we need to go for eager loading.

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();

foreach (var d in result)


{
Response.Write(d.Dname + "<br/>");
foreach (var emp in d.tbl_Emp)
{
Response.Write(emp.EName + "<br/>");
}
}

Execute this. Click search and say F10.

Let us see the query that is going to prepare at the Include line of code.

And this query is little different when we compare to earlier one.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

89

It is hitting the database only once.

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

Entity Framework - Simplified

90

This is your eager loading or early loading.

If you make LazyLoadingEnabled to true It is making n number of hits to the


database.

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.

Hope you might have enjoyed this chapter.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

91

Chapter 17 : Asp.Net Dynamic Data Entity Website

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.

Ill say OK.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

92

In solution explorer I get many different folders and files.

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

Entity Framework - Simplified

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.

Ill name it as OrganizationModel.edmx. Click on Add.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

Say Next.

www.ManzoorTheTrainer.com

94

Entity Framework - Simplified

Click Next.

www.ManzoorTheTrainer.com

95

Entity Framework - Simplified

Select all tables and click finish.

www.ManzoorTheTrainer.com

96

Entity Framework - Simplified

97

That is creating an edmx file (Entity Data Model).

2) Adding the namespace that is MicrosoftMagicWebApp

Copy this namespace and add this namespace in the Global.asax file

using MicrosoftMagicWebApp;
3) Uncomment single Line of code in Global.asax

In RegisterRoutes() method Uncomment the line DefaultModel.RegisterContext

www.ManzoorTheTrainer.com

Entity Framework - Simplified

98

4) And in place of YourDataContextType write your context class that is nothing but
your OrganizationEntities

5) Set ScaffoldAllTables=true

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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

Entity Framework - Simplified

100

I can edit an existing department

I can delete the existing department and I can go for the details of the department.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

101

And the beautiful thing is that there is a field or column called as tbl_Emp. Click on
View tbl_Emp.

It is going to give me the information of all the employees belonging to this


department.

As of now I do not have any employees.

Go back to home

www.ManzoorTheTrainer.com

Entity Framework - Simplified

102

If I click on View tbl_Emp for department QA

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.

Ill go back to home page. Ill click on tbl_Emp table.

www.ManzoorTheTrainer.com

Entity Framework - Simplified

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.

So, you can explore it more.

You can perform each and every operation.

You can modify or customize this and you can use it as you like.

www.ManzoorTheTrainer.com

This book was distributed courtesy of:

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:

To show your appreciation to the author and help others have


wonderful reading experiences and find helpful information too,
we'd be very grateful if you'd kindly
post your comments for this book here.

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

Potrebbero piacerti anche