Click here to Skip to main content
Click here to Skip to main content

Introduction to Entity Framework

By , 27 Nov 2012
Rate this:
Please Sign up or sign in to vote.

Introduction

The Entity Framework is an object-relation mapping framework. It allows developers to work directly with domain-specific objects. It frees the developers to write the storage-specific data-access code. The storage-specific schema can change without changing the application code. The rich query language support allows developers to write complex queries against a conceptual model.

This article is meant for beginner users who wanted to get started with Entity Framework. I use the Entity Framework version 5 and Visual Studio 2010 for this article. I use Northwind database but I simplify the database schema for code samples in this article.

Creating the Concept Model

In the Entity Framework, developers focus on the domain-specific objects and work directly on them. To get start, you need a concept model. You can build a model for a new database or an existing database using EF designer in Visual Studio. There are some articles talking about code-first approach or database-first approach. You can achieve that using model first and I recommend this approach.

To create the concept model for a new database

1. Create a new Class Library project.
2. Click Tools -> Library Package Manager -> Manage NuGet Packages for Solutions. Click Online on left panel. Search and install Entity Framework version 5.
3. Right click the project, then click add new item.
4. Click visual C# -> Data -> ADO.Net Entity Data Model. Name the model NorthwindModel.edmx.
5. Click empty model.
6. Then open the model to edit.

Choose empty model
Fig 1. Choose empty model

To create entity

1. Right click on designer and click add entity.
2. Add Customer entity as shown Fig 2.
3. Right click Customer entity and click add some other scalar properties.
4. Change property name and type from properties editor as shown Fig 3.

Add customer entity
Fig 2. Add customer entity

Change customer property
Fig 3. Change customer property

Repeat above steps to add Order entity. The final diagram should look like Fig 4.

Customer Order entity diagram
Fig 4. Customer Order entity diagram

To create association

1. Right click on Customer and click add Association.
2. Name association CustomerOrder and check add foreign key property box.

Add Customer Order association
Fig 5. Add Customer Order association

After adding association, the diagram should look like following.

Customer Order association
Fig 6. Customer Order association

To generate database

Right click on designer and click Generate database from Model. A file "NorthwindModel.edmx.sql" is created and can be used for database creation.

Database script file
Fig 7. Database script file

To create the concept model for an existing database

1. Choose add new item, click ADO.Net Entity Data Model and name the model "NorthwindModel.edmx".
2. Click generate from database and select only Customer and Order tables.

The diagram should look same as first approach.

Entity Class

The Entity Framework generates the database context class and POCO entity class from the concept model. The advantages of the POCO entities is that the class definitions are very simple.

Right click on EF designer and click Add Code Generation Items. Please choose DBContext template. The DBContext is the simplied API for Entity Framework. There are a couple of files generated as shown in the diagram.

Code generation
Fig 8. Class file generated by framework

Navigation property

The association between entities is implemented as Navigation property. For example, in the customer and orders relationship, a customer can have many orders. So it has a collection of Orders as Navigation property. The Order has only one Customer as Navigation property.

Complex type

The complex types can be used to organize scalar properties within entities. For example, a customer address may have street, city and zip code properties and they can be organized into a complex Address type. Right click on designer and click Refactor into New Complex Type to add a complex type.

Working with a Conceptual Model

The Entity Framework provides rich support to write complex queries against a conceptual model. You can use LINQ or SQL to query the model.

LINQ to Entities

LINQ is used to write queries against the Entity Framework conceptual model and returns entity objects. The following query gets the first customer and displays the contact name and title.

using (var context = new NorthwindEntities())
{
    // return first customer 
    var cust = (from c in context.Customers
                select c).First();
    Console.WriteLine(cust.ContactName);
    Console.WriteLine(cust.ContactTitle);
}

SQL Query

You can write the SQL query and return the entity objects. The following query prints the customer list.

using (var context = new NorthwindEntities())
{
    string sql = @"SELECT * FROM dbo.Customer";
    var query = context.Customers.SqlQuery(sql, new object[] { });
    foreach (var cust in query)
    {
        Console.WriteLine(cust.ContactName);
        Console.WriteLine(cust.ContactTitle);
    }
}

Query Projection

The queries normally return entity objects, but they may also return anonymous projections or primitive types.

var query = from c in context.Customers
            select new { ClientName = c.ContactName };
foreach (var cl in query)
{
    Console.WriteLine(cl.ClientName);
}

Loading Related Objects

There are two main ways to load related objects.
1. Lazy loading
2. Eager loading

In lazy loading, related objects are loaded when they are accessed through a navigation property. In eager loading, the include method is included in the query. The following are examples that use lazy loading and eager loading.

Lazy loading

var cust = (from c in context.Customers
            select c).First();
Console.WriteLine(cust.ContactName);
foreach (var order in cust.Orders)
{
    Console.WriteLine(order.OrderDate);
}

Eager loading
var cust = (from c in context.Customers.Include("Orders")
            select c).First();
Console.WriteLine(cust.ContactName);
foreach (var order in cust.Orders)
{
    Console.WriteLine(order.OrderDate);
}

Imported Stored Procedures

You can import store procedures to return the model objects. Right click on EF designer and click Function Import as shown in Figure 9.

Add Function Import
Fig 9. Add function import

The following code uses the imported functions.

var cust = (from c in context.GetCustomer(1)
            select c).First();
Console.WriteLine(cust.ContactName);

Model with Stored Procedures

You can specify stored procedures to modify entity data. These stored procedures replace the methods generated by the Entity Framework. Right click on designer and click Stored Procedure Mapping. Map insert, delete and update action with stored procedures as shown in Fig 10.

Add stored procedure mapping
Fig 10. Add stored procedure mapping

Local Data

The query data is cached and tracked by the context. The data can be marked in different state such as Added, Updated or Deleted. Normally the data changes are tracked automaticalletly, but it can be turned off through Configuration and called explicitly. The following code shows how to track manually.

// Set auto detect off and call manually 
context.Configuration.AutoDetectChangesEnabled = false;
DbChangeTracker tracker = context.ChangeTracker;

// get a customer object
Customer cust = context.Customers.First();

// add a order to it
Order od = new Order();
od.CustomerID = 1;
od.OrderDate = DateTime.Now;
cust.Orders.Add(od);

// the new change is not tracked
int cnt = tracker.Entries<order>().ToList().Count;
Console.WriteLine(cnt);

// call detect changes and changes are tracked by context
context.ChangeTracker.DetectChanges();
cnt = tracker.Entries<order>().ToList().Count;
Console.WriteLine(cnt);
</order></order>

Summary 

This article gives you a simple introduction to Entity Framework so you can start working and diving into more detail.

Please mark your votes and suggestions. I hope you have enjoyed this article.

License

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

About the Author

Alex_Xia
Software Developer (Senior) YP (Formerly ATTInteractive)
United States United States
Specialized in C# ASP.Net web development, data warehouse and business intelligent.

Comments and Discussions

 
SuggestionPoor Presentation!!! PinmemberDebopam Pal11-Nov-13 0:40 
GeneralRe: Poor Presentation!!! PinmemberTittle Joseph31-Dec-13 0:22 
GeneralMy vote of 4 PinmemberGianluca Maria Marcilli23-Jul-13 10:57 
QuestionWhat can I do more? PinmemberMark Shneider7-May-13 10:30 
QuestionThanks Pinmemberkarland2-May-13 1:08 
GeneralThanks PinmemberHexxellor30-Nov-12 9:00 

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 | Mobile
Web04 | 2.8.140421.2 | Last Updated 27 Nov 2012
Article Copyright 2012 by Alex_Xia
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid