Click here to Skip to main content
11,432,428 members (65,238 online)
Click here to Skip to main content

An Introduction to Entity Framework for Absolute Beginners

, 9 Apr 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
An introduction to Entity Framework for absolute beginners.

Introduction

This article introduces Entity Framework to absolute beginners. The article is meant for developers who are primarily using ADO.NET to write their data access layers. Many experienced developers will find this article very basic but since the article is written from the perspective of beginners, I've tried to keep things simple.

Background

ADO.NET is a very strong framework for data access. ADO.NET has been around since many years and there are a lot of systems running over ADO.NET. Developers who are totally oblivious to the concept of ORMs will probably be asking "What is Entity Framework? What are the benefits of using it and is it an alternative to ADO.NET?"

Well, to answer the first question about what is Entity Framework, Entity Framework is an Object Relational Mapper (ORM). It basically generates business objects and entities according to the database tables and provides the mechanism for:

  1. Performing basic CRUD (Create, Read, Update, Delete) operations.
  2. Easily managing "1 to 1", "1 to many", and "many to many" relationships.
  3. Ability to have inheritance relationships between entities.

and to answer the second question, the benefits are:

  1. We can have all data access logic written in higher level languages.
  2. The conceptual model can be represented in a better way by using relationships among entities.
  3. The underlying data store can be replaced without much overhead since all data access logic is present at a higher level.

and finally, the last question that whether it is an alternative to ADO.NET, the answer would be "yes and no". Yes because the developer will not be writing ADO.NET methods and classes for performing data operations and no because this model is actually written on top of ADO.NET, meaning under this framework, we are still using ADO.NET. So let us look at the architecture of Entity Framework (diagram taken from MSDN):

Entity framework article image

Using the code

Let's try to understand the ease of use that Entity Framework provides by performing simple CRUD operations. Once we look at the code and how effortlessly and efficiently we can do these operations, the benefits of Entity Framework will become quite obvious.

Creating the database

Let's have a simple database with one table. Let's create a simple table for Contacts and we will perform CRUD operations on this table.

Entity framework article image

Adding the Entity Model to the Website

Once we have the database ready, we can add the entity model to our website. We can do this by adding an ADO.NET Entity Data Model to the website.

Entity framework article image

Once we select to add this data model to our website, we will have to select the approach we want to take for our Model's contents.

Entity framework article image

What this selection means is that we can either choose to generate the entity model from an existing database schema or we can design the entity model here and then later hook it up to the database. Since we already have the database ready, we will use the first option. Once the Model is generated, the Entity for each table is generated. The generated entity for our contact table is:

Entity framework article image

Also, the classes for performing database operations are also created. We just need to know how to use these classes to perform database operations.

Entity framework article image

Insert operation

Let us create a simple page to perform an insert operation.

Entity framework article image

Now once the user chooses to insert the values into the database, the actual data operation can be performed by using the AddObject method of the Model class entity collection. The following code snippet show how to perform the insert.

Contact con = new Contact();
con.fname = TextBox1.Text;
con.lname = TextBox2.Text;
con.phone = TextBox3.Text;

ContactsDb db = new ContactsDb();
db.Contacts.AddObject(con);
db.SaveChanges();

This will insert the record into the table. You can notice the simplicity and efficiency of the code we wrote to perform the insertion.

Reading all the records

There are scenarios when we want to read all records. Let's say we are making a page that will display all the contact information in a single page.

Entity framework article image

We can retrieve the collection of Entities using the Model object to achieve this. The code snippet below will show how that can be done.

ContactsDb db = new ContactsDb();
Repeater1.DataSource = db.Contacts;
Repeater1.DataBind();

Selecting a specific record

If we want to select a specific record from the table, we can use the SingleOrDefault method on the Model's entities collection. Let's say we want the functionality of updating/deleting a record on a single page then we will first have to select the record based on the ID, then update/delete the selected record.

Entity framework article image

Selection of any particular record (Contact) based on ID can be done as:

int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);

Once this code is executed, the Contact object will contain the required values.

Updating the record

If we want to update a record, then a simple update operation can be performed as:

int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p =>  p.id == idToupdate);

con.phone = TextBox1.Text;
db.SaveChanges();

Once this code executes, the value of phone number will be updated by a new value which is retrieved from TextBox1.

Deleting a record

If we want to delete a particular record then we can perform a delete operation by using the DeleteObject function. The following code snippet demonstrates the same:

//delete this contact
int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);

db.Contacts.DeleteObject(con);
db.SaveChanges();

Now that we have the basic CRUD operations performed on the database using the Entity Framework.

A note on Relationships and Lazy Loading

To understand the Entity Framework we need to understand some things like naming conventions, relationships between tables, and relationships between entities. Also, the concept of lazy loading once fully understood will give the power to the developer to use the Entity Framework efficiently.

Note: Since this is an introductory article on Entity Framework we have not discussed these things. Perhaps we will discuss them in a separate article.

Points of interest

Entity Framework has been in use for some time now. But there are many developers who are still getting started with Entity Framework. This article was meant as an overview of the Entity Framework. This should not be treated as a complete tutorial. Also, the code written is very simple and there is a lot of scope for optimization but since the idea here is to understand Entity Framework, I tried to keep the code simple and readable rather and optimal.

Note: To run the solution, please change the database path of ConnectionString in the web.config file.

History

  • 09 April 2012: First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rahul Rajat Singh
Architect
India India
I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.
  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionDidn't work. Pin
Member 935277517-Jul-14 12:18
memberMember 935277517-Jul-14 12:18 
GeneralMy vote of 2 [modified] Pin
Mark Storen17-Jul-14 3:07
memberMark Storen17-Jul-14 3:07 
GeneralNice and simple Pin
Bhavik_Patel2-Jul-14 22:05
professionalBhavik_Patel2-Jul-14 22:05 
QuestionSimple and Easy [modified] Pin
SaqibAshraf2-Jul-14 9:00
memberSaqibAshraf2-Jul-14 9:00 
QuestionExcellent Article Pin
Mohammed Dawood Ansari29-Jun-14 1:38
memberMohammed Dawood Ansari29-Jun-14 1:38 
Generalperfect Pin
anfil10-Jun-14 9:20
memberanfil10-Jun-14 9:20 
QuestionNice article Pin
Satyavir Yadav India26-May-14 2:09
memberSatyavir Yadav India26-May-14 2:09 
Questioni am using entitity framwork with aspx form but there is problem Pin
muhammadjavaid13-May-14 22:04
membermuhammadjavaid13-May-14 22:04 
GeneralExcellent article : 5* Pin
Member 411179413-May-14 9:43
memberMember 411179413-May-14 9:43 
GeneralNice Article Pin
Dinesh Satpute11-Apr-14 21:04
memberDinesh Satpute11-Apr-14 21:04 
GeneralVery Good Artical Pin
keyur soni27-Mar-14 19:34
memberkeyur soni27-Mar-14 19:34 
QuestionUnable to open project Pin
Member 1019633827-Feb-14 1:43
memberMember 1019633827-Feb-14 1:43 
QuestionNice article Pin
Bhagwant Singh22-Feb-14 7:09
memberBhagwant Singh22-Feb-14 7:09 
GeneralMy vote of 4 Pin
byff11-Feb-14 10:17
memberbyff11-Feb-14 10:17 
QuestionObjects not being created Pin
byff11-Feb-14 10:16
memberbyff11-Feb-14 10:16 
QuestionExcellent Job Pin
Deepak K Gupta5-Feb-14 21:12
memberDeepak K Gupta5-Feb-14 21:12 
QuestionNot able to process it. Pin
Abhisar Garg30-Jan-14 20:49
memberAbhisar Garg30-Jan-14 20:49 
QuestionQs on Oracle DB? Pin
Member 105022773-Jan-14 14:49
memberMember 105022773-Jan-14 14:49 
QuestionMy vote of 5* Pin
Mas1110-Dec-13 19:34
memberMas1110-Dec-13 19:34 
AnswerRe: My vote of 5* Pin
Rahul Rajat Singh10-Dec-13 19:38
mvpRahul Rajat Singh10-Dec-13 19:38 
GeneralRe: My vote of 5* Pin
Mas1110-Dec-13 20:09
memberMas1110-Dec-13 20:09 
QuestionQuestion on the delete code Pin
Ken Kazinski4-Dec-13 2:37
memberKen Kazinski4-Dec-13 2:37 
AnswerRe: Question on the delete code Pin
Rahul Rajat Singh4-Dec-13 3:11
mvpRahul Rajat Singh4-Dec-13 3:11 
GeneralMy vote of 5 Pin
Member 1042689526-Nov-13 2:14
memberMember 1042689526-Nov-13 2:14 
Generalthanks Pin
vahid124-Nov-13 20:41
membervahid124-Nov-13 20:41 
Generalgood Job Pin
ead mahmoud13-Nov-13 3:31
memberead mahmoud13-Nov-13 3:31 
SuggestionCode is not documented!!! Pin
Debopam Pal11-Nov-13 1:24
memberDebopam Pal11-Nov-13 1:24 
GeneralRe: Code is not documented!!! Pin
Member 1048410123-Dec-13 8:10
memberMember 1048410123-Dec-13 8:10 
GeneralRe: Code is not documented!!! Pin
Member 107373199-Apr-14 10:06
memberMember 107373199-Apr-14 10:06 
GeneralMy vote of 3 Pin
Anish V17-Oct-13 22:25
memberAnish V17-Oct-13 22:25 
GeneralRe: My vote of 3 Pin
rperetz28-Oct-13 4:23
memberrperetz28-Oct-13 4:23 
GeneralRe: My vote of 3 Pin
Anish V30-Oct-13 2:17
memberAnish V30-Oct-13 2:17 
GeneralRe: My vote of 3 Pin
LittleBlueBird4-Nov-13 4:45
memberLittleBlueBird4-Nov-13 4:45 
GeneralRe: My vote of 3 Pin
Debopam Pal11-Nov-13 1:14
memberDebopam Pal11-Nov-13 1:14 
Questionvote of 5 Pin
Taner Riffat5-Oct-13 18:28
memberTaner Riffat5-Oct-13 18:28 
Question[My vote of 1] 1 Pin
Member 102222012-Oct-13 0:56
memberMember 102222012-Oct-13 0:56 
SuggestionRe: [My vote of 1] 1 Pin
Debopam Pal11-Nov-13 1:29
memberDebopam Pal11-Nov-13 1:29 
Question[My vote of 1] Very poor Pin
msdevtech18-Sep-13 10:48
membermsdevtech18-Sep-13 10:48 
GeneralMy vote of 5 Pin
Shail Mishra17-Sep-13 6:52
memberShail Mishra17-Sep-13 6:52 
GeneralMy vote of 5 Pin
Member 837408214-Sep-13 1:48
memberMember 837408214-Sep-13 1:48 
QuestionClasses for DB operations Pin
shacha4-Sep-13 22:13
membershacha4-Sep-13 22:13 
Questionhelp with a trick :) Pin
joni50para30-Aug-13 3:28
memberjoni50para30-Aug-13 3:28 
GeneralMy vote of 5 Pin
Ngo Viet Hung27-Aug-13 21:16
memberNgo Viet Hung27-Aug-13 21:16 
GeneralMy vote of 5 Pin
archana naik26-Aug-13 2:22
memberarchana naik26-Aug-13 2:22 
QuestionNeed some help Pin
Mathi2code1-Aug-13 3:29
memberMathi2code1-Aug-13 3:29 
GeneralMy vote of 5 Pin
sajjad nawaz18-Jul-13 23:00
membersajjad nawaz18-Jul-13 23:00 
QuestionThanks Pin
mdastlan17-Jul-13 19:58
membermdastlan17-Jul-13 19:58 
GeneralMy vote of 5 Pin
Sridhar Patnayak26-Jun-13 3:16
memberSridhar Patnayak26-Jun-13 3:16 
GeneralMy vote of 1 Pin
Hitesh Asodiya19-Jun-13 22:53
memberHitesh Asodiya19-Jun-13 22:53 
GeneralRe: My vote of 1 Pin
Rahul Rajat Singh19-Jun-13 23:46
mvpRahul Rajat Singh19-Jun-13 23:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150428.2 | Last Updated 9 Apr 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid