Click here to Skip to main content
12,631,365 members (31,842 online)
Click here to Skip to main content
Add your own
alternative version

Stats

314.4K views
13.8K downloads
134 bookmarked
Posted

Entity Framework Tutorial for Beginners

, 7 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
A simple tutorial for beginners to learn the basics of Entity Framework. It will teach you how to perform CRUD operations using EF.

Introduction

In this article, we will learn the basics of Entity Framework by creating a sample application. This article is for those programmers who have some experience in creating ASP.NET applications, but are new to the Entity Framework. Here, I will explain:

  • How to create an Entity Data Model
  • Perform CRUD operations
  • Use Stored Procedures

Here is a quick view of the application that you are going to create:

Background

There are many articles that will teach the basics of Entity Framework. But in this post, you are going to learn by creating a simple one page application.

What is Entity Framework?

  • Object/Relational Mapping (ORM) framework
  • Work with database as domain-specific objects
  • Retrieve and manipulate data as strongly typed objects

Using the Code

The application is created using Visual Studio 2010. The complete code of the application is attached here, which you can download and test. The sample code contains relevant comments to explain every step. Let's walk through the application step by step.

Start a New Project

Start a new "ASP.NET Web Application" as shown below:

Create Database

Here, we are going to use a very simple database with name LearnEF with only one table. The table Employee will have a list of employees with basic information about each employee. You may use the following script to create the table and a stored procedure used in this application.

CREATE TABLE Employee
(
    EmpId        int NOT NULL IDENTITY(1,1) PRIMARY KEY,
    HREmpId        nvarchar(10),
    FirstName    nvarchar(30),
    LastName    nvarchar(30),
    Address        nvarchar(30),
    City        nvarchar(30)
)
GO
 
--SearchEmployee '', ''
CREATE PROCEDURE SearchEmployee
(
    @FirstName        varchar(30),
    @City            varchar(30)
)
AS
BEGIN
    DECLARE @query    nvarchar(1000)
 
    SET @query = 'SELECT * FROM Employee e'
    SET @query = @query + ' WHERE 1=1'
 
    IF @FirstName != ''
        SET @query = @query + ' AND FirstName LIKE ''' + @FirstName + '%'''
 
    IF @City != ''
        SET @query = @query + ' AND City LIKE ''' + @City + '%'''
 
 
    EXEC (@query)
END
GO

NOTE: Some of my friends will be quick to note that above SP is susceptible to SQL Injection attacks and I agree with this. This is because I have tried to keep the code simple and easy to understand, moreover this article is about entity framework. Please ignore this issue and if you really care about this, please refer to an advanced tutorial related to SQL injection.

Create Entity Data Model

Now, let's create the entity data model. Here are the step-by-step details:

  1. Right-click on the project name, select Add -> New Item.
  2. Select the Data tab from left pane, then select ADO.NET Entity Data Model.
  3. Name it as LearnEF.edmx. Click Add.
  4. Select Generate from database in the Entity Data Model Wizard.
  5. In the next window, set the connection properties for your database and click Next.
  6. The next window will show you the objects in your database. Select the table Employee and the stored procedure SearchEmployee.

  7. Click Finish. If you have completed the above steps successfully, you will see your EDM in design mode as shown below:

Note: The name of database used in this article is LearnEF and hence the system will generate an ObjectContext class with name LearnEFEntities. Similarly, the system will create a class of type EntityObject with name Employee based upon the table name. As shown in the above snapshot, there is a stored procedure with name SearchEmployee, so the class LearnEFEntities will expose a corresponding method with name SearchEmployee.

If the name of your database/table/stored procedure is different, then remember to modify the code accordingly.

Insert a New Record

To insert a new record:

  1. Create an object of the object context, i.e., LearnEFEntities:
    LearnEFEntities db = new LearnEFEntities();
  2. Create an object of Employee class, e.g.:
    Employee objEmp = new Employee();  
  3. Set the values of all the columns which are exposed in form of properties like:
    objEmp.FirstName = txtFirstName.Text; 
  4. Add object to the Employees collection in ObjecContext and call SaveChanges to actually insert the record into the table:
    db.Employees.AddObject(objEmp); 
    db.SaveChanges();  

Here is a complete code snippet:

LearnEFEntities db = new LearnEFEntities();

Employee objEmp = new Employee();
objEmp.HREmpId = txtHREmpId.Text;
objEmp.FirstName = txtFirstName.Text;
objEmp.LastName = txtLastName.Text;
objEmp.Address = txtAddress.Text;
objEmp.City = txtCity.Text;
 
db.Employees.AddObject(objEmp);
db.SaveChanges();

Read from Employee table and populate GridView

To read data from the Employee table, we will use a LINQ query that will fetch data from the Employees collection. It will return a generic List of objects of type Employee, i.e. List<Employee>. The complete code to read data from the Employee table and then bind a drop-down list and GridView is given below:

LearnEFEntities db = new LearnEFEntities();
 
var empQuery = from emp in db.Employees
                select emp;
List<Employee> empList = empQuery.ToList();
 
ddlEmployee.DataSource = empList;
ddlEmployee.DataValueField = "EmpId";
ddlEmployee.DataTextField = "FirstName";
ddlEmployee.DataBind();
 
ddlEmployee.Items.Insert(0, new ListItem("--Add New--", "0"));
 
//bind grid
GridView1.DataSource = empList;
GridView1.DataBind();

Update an Employee Record

To update a record in the database, we will perform the following three steps:

  1. Read a record from the database. The process is similar as explained in the above section.
  2. Set the new values of the properties (columns) that we want to modify.
  3. Save the changes into the database using SaveChages method.
//Read the record from the database.
LearnEFEntities db = new LearnEFEntities();

//following query will fetch a record based upon the EmpID passed through local variable empId
var empQuery = from emp in db.Employees
                where emp.EmpId == empId
                select emp;
Employee objEmp = empQuery.Single();

//set the new values of the columns (properties), based upon the values entered using the text boxes
objEmp.HREmpId = txtHREmpId.Text;
objEmp.FirstName = txtFirstName.Text;
objEmp.LastName = txtLastName.Text;
objEmp.Address = txtAddress.Text;
objEmp.City = txtCity.Text;

//save your changes into the database
db.SaveChanges();

How to Delete a Record

There are multiple ways to delete a record using entity framework. The steps involved in the approach that we follow are:

  1. Create a new instance of the entity object that you want to delete and set the value of the property that will be used to filter the records to be deleted. In this case, we are going to create a new Employee and set the value of its EmpID property.
  2. Attach the object to the corresponding collection or entity set in object context.
  3. Mark the object for deletion using the DeleteObject() method.
  4. Delete the record from the database using the SaveChanges() method.

The following code will clarify the above mentioned steps to delete a record:

LearnEFEntities db = new LearnEFEntities();
 
//create a new object using the value of EmpId
Employee objEmp = new Employee() { EmpId = empId };
 
//attach object in the entity set
db.Employees.Attach(objEmp);

//mark the object for deletion
db.Employees.DeleteObject(objEmp);
 
//save changes
db.SaveChanges(); 

How to use Stored Procedures in Entity Framework

We can also use stored procedures in the entity framework. To use a stored procedure, we have to first add it in our entity data model and then generate a method for that stored procedure. Note that while creating the entity data model in the beginning of this article, we selected a stored procedure SearchEmployee. Now we are going to add search functionality using a stored procedure. For this, we have to add a method for the SP and define its return type, which is a collection of Employee objects in our case. Here are the steps:

  1. Double click LearnEF.edmx
  2. Right click in the main pane, then select Model Browser.
  3. Expand Stored Procedure node in model browser, right click SearchEmployee stored procedure, then click Add Function Import.

  4. Set "Returns a collection of" value to Entities and select Employee from drop-down.
  5. Click OK and now we are ready to use this stored procedure.

In the above steps, we have actually added a method SearchEmployee in our object context that will return a List of type Employee. The statement to use this method will be:

List<Employee> empList = db.SearchEmployee(txtSrchFirstName.Text, txtSrchCity.Text).ToList();

The following code snippet can be used to search employees and bind a grid:

List<Employee> empList = db.SearchEmployee(txtSrchFirstName.Text, txtSrchCity.Text).ToList();
 
//bind grid
GridView1.DataSource = empList;
GridView1.DataBind(); 

License

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

Share

About the Author

Code Help 2014
Software Developer (Senior)
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionGood ! Pin
SusannePorte21-Nov-16 22:25
memberSusannePorte21-Nov-16 22:25 
QuestionAwesome Pin
SophieVerdier15-Nov-16 23:23
memberSophieVerdier15-Nov-16 23:23 
QuestionThe name 'empId' does not exist in the current context Pin
Smart_Mohit18-Aug-16 0:29
professionalSmart_Mohit18-Aug-16 0:29 
GeneralADO.NET: Entity Framework vs DataReader Pin
Member 1267225415-Aug-16 10:52
memberMember 1267225415-Aug-16 10:52 
QuestionVery Helpful Pin
Jeremy Hays9-Jun-16 4:02
memberJeremy Hays9-Jun-16 4:02 
PraiseGood Article. Would Recommend following article too. Pin
m.m.k13-Apr-16 8:55
memberm.m.k13-Apr-16 8:55 
QuestionException while running the code Pin
Member 112418736-Apr-16 3:00
memberMember 112418736-Apr-16 3:00 
QuestionDoubt over AddObject method Pin
Member 112418736-Apr-16 0:59
memberMember 112418736-Apr-16 0:59 
QuestionEntity Framework BulkInsert fails if a record error occors Pin
shraddha chauhan30-Nov-15 11:54
membershraddha chauhan30-Nov-15 11:54 
QuestionError while executing code Pin
Member 1082319822-Sep-15 20:22
memberMember 1082319822-Sep-15 20:22 
AnswerRe: Error while executing code Pin
Code Help 201424-Sep-15 3:04
professionalCode Help 201424-Sep-15 3:04 
QuestionMy vote of 3 Pin
pradeep shet26-Jul-15 1:33
memberpradeep shet26-Jul-15 1:33 
AnswerRe: My vote of 3 Pin
Code Help 201427-Jul-15 20:49
memberCode Help 201427-Jul-15 20:49 
QuestionError while executing stored procedure. Pin
Member 1122029823-Jul-15 1:24
professionalMember 1122029823-Jul-15 1:24 
AnswerRe: Error while executing stored procedure. Pin
Code Help 201423-Jul-15 1:56
memberCode Help 201423-Jul-15 1:56 
GeneralRe: Error while executing stored procedure. Pin
Member 1122029823-Jul-15 19:43
professionalMember 1122029823-Jul-15 19:43 
QuestionStraight to the point Pin
Enemali William16-May-15 17:46
professionalEnemali William16-May-15 17:46 
AnswerRe: Straight to the point Pin
Code Help 201419-May-15 1:24
memberCode Help 201419-May-15 1:24 
QuestionZip file does not uncompress Pin
Member 844819826-Mar-15 8:16
memberMember 844819826-Mar-15 8:16 
AnswerRe: Zip file does not uncompress Pin
Code Help 201431-Mar-15 2:04
memberCode Help 201431-Mar-15 2:04 
GeneralRe: Zip file does not uncompress Pin
Member 844819831-Mar-15 8:34
memberMember 844819831-Mar-15 8:34 
BugDeleteObject is not a method in entity Pin
Aslam Jarwar23-Mar-15 9:41
memberAslam Jarwar23-Mar-15 9:41 
GeneralRe: DeleteObject is not a method in entity Pin
Code Help 201423-Mar-15 22:00
memberCode Help 201423-Mar-15 22:00 
GeneralRe: DeleteObject is not a method in entity Pin
tamer_az18-May-15 15:05
membertamer_az18-May-15 15:05 
GeneralRe: DeleteObject is not a method in entity Pin
Member 114867296-Apr-16 4:05
memberMember 114867296-Apr-16 4:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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
Web01 | 2.8.161205.3 | Last Updated 7 Jul 2014
Article Copyright 2014 by Code Help 2014
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid