Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Programming ADO.NET Entity Framework 4.0, Part 1

Leverage the new and enhanced features of Entity Framework 4.0 to design and implement scalable applications.


advertisement
There are plenty of Object Relational Mapping tools available now. You have nHibernate, LINQ to SQL, Entity Spaces, and what not. The ADO.NET Entity Framework is an extended Object Relational Mapping Tool from Microsoft that has over the past few years become increasingly popular and is being widely used these days.

The latest version of this tool is Entity Framework 4.0 that ships with Visual Studio 2010. This series of articles presents the features of Entity Framework, a knowhow on the new features in Entity Framework 4 and how you can program it in your applications.

Pre-Requisites

[login]

To work with Entity Framework and the code examples illustrated in this article, you should have the following installed in your system:

  • Visual Studio 2008 with SP1
  • Entity Framework Version 4



Alternatively, you can simply have Visual Studio 2010 in your system – it comes with Entity Framework 4 by default. You would also need SQL Server 2008 and AdventureWorks and Northwind databases.

What is the ADO.NET Entity Framework and why is it useful?

The ADO.NET Entity Framework is essentially used to abstract the object model of an application from its relational or logical model. You can use it to objectify your application's data and isolate the logical or relational model of your application from the object model.

The new features and enhancements in ADO.NET Entity Framework 4.0 include:

  • Persistence Ignorance
  • Lazy Loading
  • Better N-Tier Support
  • Model-First and Code Only Development
  • Built-In Functions, UDFs and Model Defined Functions

Components of the ADO.NET Entity Framework

The ADO.NET Entity Framework includes the following components:

1.      The Entity Data Model – An entity relationship data model

2.      LINQ to Entities – This is used to query the Entity Data Model using strongly typed LINQ queries

3.      Entity Client – This is a store independent data provider that is used to query the Entity Data Model.

4.      The Object Services Layer – This is used to query data from the Entity Data Model in a generic manner.

The Entity Data Model is an Entity Relationship Model that depicts the entities and their relationships. It comprises of a storage schema, a conceptual schema and a mapping schema together with the entity classes and is represented physically as a .edmx file or as a collection of .xml files where each .xml file represents the CSDL, MSL or the SSDL layers.

The Entity Data Model is basically comprised of the following three layers:

  • Conceptual Layer – Represented using CSDL (Conceptual Data Language)
  • Storage Layer – Represented using SSDL (Store-specific Data Language)
  • Mapping Layer – Represented MSL (Mapping Schema Language)

The CSDL is the conceptual or the C-Space layer that comprises of EntityContainer, EntitySets, AssociationSets, AssociationTypes, EntityTypes, Relationships and Functions. It is queried using Entity SQL. The layer beneath the CSDL is the C-S Mapping Layer or the MSL. It is typically used to map the CSDL and SSDL layers. The SSDL is the logical or the S-Space and comprises of Tables, StoredProcedures, Views and Functions. It is queried using the standard ADO.NET providers.

You can create an Entity Data Model using the Entity Data Model Designer in Visual Studio or using the command line utility called EdmGen.exe - the Entity Data Model Designer. In the section that follows we will learn how to program against the Entity Data Model.

Programming the Entity Data Model

To query data from the Entity Data Model, you have three choices: LINQ to Entities, Object Services and using the Entity Client provider. In this section we will briefly discuss each.

You can use LINQ to Entities to query your business objects in a strongly typed manner. The following is an example of a typical LINQ to Entities query that displays EmployeeID from the Employees table of the AdventureWorks database.

AdventureWorksEntities dataContext = new AdventureWorksEntities(); var result = from employee in dataContext.Employees select employee; foreach (var emp in result) Console.WriteLine (result.EmployeeID);

You also have the Entity Client provider - a storage independent provider for writing and executing your queries against the Entity Data Model much the same way you do using any other ADO.NET provider. You can use the text-based query language Entity SQL in conjunction with the Entity Client provider to query data or perform CRUD operations on your data.

using (EntityConnection entityConnection = new EntityConnection("Name=NorthwindEntities")) { try { entityConnection.Open(); EntityCommand entityCommand = entityConnection.CreateCommand(); entityCommand.CommandText = "NorthwindEntities.AddNewEmployee"; entityCommand.CommandType = CommandType.StoredProcedure; entityCommand.Parameters.AddWithValue("FirstName", "Joydip"); entityCommand.Parameters.AddWithValue("LastName", "Kanjilal"); entityCommand.Parameters.AddWithValue("Address", "Begumpet"); entityCommand.Parameters.AddWithValue("City", "Hyderabad"); entityCommand.Parameters.AddWithValue("Country", "INDIA"); entityCommand.ExecuteNonQuery(); } catch (Exception ex) {    Console.WriteLine("Error: "+ex.Message); } }

Note that stored procedures are represented as functions in the Entity Data Model. Before you can use stored procedures to perform CRUD operations, you'll need to define and map these functions to a corresponding Insert, Update, or Delete operations respectively.

You can also get the native SQL from an Entity Command instance. To do this, you'll need to call the ToTraceString() method on the EntityCommand instance as shown in the code listing below:

String sqlString = String.Empty;

using (EntityConnection entityConnection = new EntityConnection("Name=NorthwindEntities")) {

try

{ entityConnection.Open(); EntityCommand entityCommand = entityConnection.CreateCommand(); entityCommand.CommandText = "NorthwindEntities.EditEmployee"; entityCommand.CommandType = CommandType.StoredProcedure;

//Some code

sqlString = entityCommand.ToTraceString();

   entityCommand.ExecuteNonQuery();

catch (Exception ex) {

       Console.WriteLine("Error: "+ex.Message);

      }

}
The Object Services Layer allows you to query data in a more generic way. The Object Services Layer uses an Object Query instance internally to process and execute the queries. The Object Services Layer provides support for:

Change tracking, Lazy loading, Optimistic concurrency, Identity resolution, etc.

The following code listing shows how you can query the Entity Data Model for AdventureWorks database and display a list of all the EmployeeIDs from the Employees table.

using (ObjectContext dataContext = new ObjectContext("Name= AdventureWorksEntities"))

        {

            var result = from employee in dataContext.CreateQuery<Employee>("AdventureWorksEntities") select employee;

            foreach (Employee emp in result)

            {

                Console.WriteLine(emp.EmployeeID);        

            }

        }

Summary

This article, the first in the series of two articles on Programming Entity Framework, presented the goals and basic features of Entity Framework. We will discuss more on how you can program Entity Framework 4.0 in the next and concluding part of this series. So, stay tuned!



   
Joydip Kanjilal has over 10 years of industry experience with C, C++, Java, C#, VB, VC++, ASP.Net, XML, Design Patterns, UML, etc. He currently works as a senior project leader in a reputable multinational company in Hyderabad, India, and has contributed articles on .NET and related technologies to www.aspalliance.com.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap