Thursday, January 16, 2014

Entity Framework tutorial


What is Entity Framework?
Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database and working with the results in addition to DataReader and DataSet.

what is O/RM framework and why do we need it?

ORM is a tool for storing data from domain objects to relational database like MS SQL Server in an automated way without much programming.
 O/RM includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects maps to relational database objects (tables, views & storedprocedures). ORM helps us to keep our database design separate from our domain class design. This makes application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so developer doesn’t need to write it manually.

 

Entity Framework vs LINQ-to-SQL:

You may think that what is the difference between Entity Framework and LINQ to SQL which does that same thing. There are some differences between Entity Framework and L2S.Entity framework has a full provider model. It supports not only SQL Server but also other database like Oracle, DB2, MySQL etc.

·         Most of the time L2S classes must be one-to-one with database objects e.g. Customer class can be mapped only with Customer table. Where as in Entity Framework you can map your domain class with multiple tables using various inheritance strategies like table per type (class) or table per hierarchy of classes etc.

·         You can have multiple modeling techniques using Entity Framework 4.1 like code first, model first or database first.

·         Microsoft has long term strategy to support and integrate Entity Framework with multiple Microsoft products.

 Entity Framework Architecture

Entity Framework Architecture

EDM (Entity Data Model): EDM consist three main parts- Conceptual model, Mapping and Storage model.

 

 

Conceptual Model: Conceptual model is your model classes and their relationships. This will be independent from your database table design.

 

Storage Model: Storage model is your database design model which includes tables, views, stored procedures and their relationships and keys.

 

Mapping: Mapping consist information about how your conceptual model is mapped to storage model.

 

LINQ to Entities:LINQ to Entities is query language used to write queries against the object model. It returns entities which are defined in the conceptual model. You can use your LINQ skills here.

 

Entity SQL:Entity SQL is again a query language same as LINQ to Entities. However it is little more difficult than L2E and also developer need to learn it separately.

 

Object Service:Object service is a main entry point for accessing data from database and to return it back. Object service is responsible for materialization which is process of converting data returned from entity client data provider (next layer) to an entity object structure.

 

Entity Client Data Provider:The main responsibility of this layer is to convert L2E or Entity SQL queries into SQL query which is understood by underlying database. It communicates with ADO.Net data provider which in turn sends or retrieves data from database.

 

ADO.Net Data Provider:This layer communicates with database using standard ADO.Net.

 

 

Querying with EDM:

You can query EDM mainly by three ways, 1) LINQ to Entities 2) Entity SQL 3) Native SQL


 

1) LINQ to Entities: L2E query syntax is easier to learn than Entity SQL. You can use your LINQ skills for querying with EDM. Following code snippet shows how you can query with EDM created in previous step.

using (var objCtx = new SchoolDBEntities())
    {
        var schoolCourse = from cs in objCtx.Courses
                           where cs.CourseName == "Course1"
                           select cs;
        Course mathCourse = schoolCourse.FirstOrDefault<Course>();
        IList<Course> courseList = schoolCourse.ToList<Course>();
 
        string courseName = mathCourse.CourseName;

    }

 

2) Entity SQL: Another way to create a query, instead of LINQ to Entities, is by using the Entity Framework’s Object Services directly. You can create an ObjectQuery directly combined with the Entity Framework’s T-SQL-like query language, called Entity SQL, to build the query expression.



Following code snippet shows same query result as L2E query above.  

 
    //Querying with Object Services and Entity SQL
    using (var objCtx = new SchoolDBEntities())
    {
        string sqlString = "SELECT VALUE cs FROM SchoolDBEntities.Courses
                            AS cs WHERE cs.CourseName == 'Maths'";
        ObjectQuery<Course> course = objCtx.CreateQuery<Course>(sqlString);
        Course coursename1 = course.FirstOrDefault<Course>();
    }

 

 

3)Native SQL In the Entity Framework v4 new methods ExecuteFunction(), ExecuteStoreQuery() and ExecuteStoreCommand() were added to the class ObjectContext. So you can use these methods to execute Native SQL to the database as following:

 

   
    //Querying with native sql           
    using (var objCtx = new SchoolDBEntities())
        {
            //Inserting Student using ExecuteStoreCommand
            int InsertedRows = objCtx.ExecuteStoreCommand("Insert into Student(StudentName,StandardId) values('StudentName1',1)");
 
            //Fetching student using ExecuteStoreQuery
            var student = objCtx.ExecuteStoreQuery<Student>("Select * from Student where StudentName = 'StudentName1'", null).ToList();
 
        }  
   

 

 

 

 


Types of Entities in Entity Framework:

There are four types of Entities in Entity Framework 4.x,

 1) EntityObject

2) POCO

3) POCO Proxy

4) Self-Tracking Entities

Each entity can have two types of properties

1.Scalar properties

Scalar properties are properties whose actual values are contained in the entity

2.Navigation properties

Navigation properties are pointers to other related entities

 

EntityObject: By default, the ADO.NET Entity Data Model tools generate EntityObject derived entities. If you check entities created in previous step, it is of this type. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework. If you are working with architectures that require persistence ignorance (for example, test- driven development or domain-driven development) or you have existing domain classes, consider using POCO or POCO proxies.

 

POCO (Plain Old CLR Object): POCO class is the class which doesn’t depend on any framework specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects”. The Entity Framework 4.0 enables you to use existing .net classes together with the data model without making any modifications to the existing .net classes. These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as EntityObject derived entities .


Following is a Student POCO class:

public class Student
    {
        public int StudentID { get; set; }
 
        public string StudentName{ get; set; }
 
        public Standard Standard{ get ; set; }
 
        public StudentAddress StudentAddress{ get ; set; }
 
        public IList<Course> Courses{ get; set; }
 
    }

 

POCO Proxy: POCO Proxy is a runtime proxy class of POCO entity. POCO entity becomes POCO Proxy entity if it meets certain requirements to enable lazy loading proxy and instant change tracking. It adds some methods at runtime to your POCO class which does instant change tracking and lazy loading stuff.
POCO entity should meet the following requirement to become POCO proxy:

1.     A custom data class must be declared with public access.

2.     A custom data class must not be sealed (NotInheritable in Visual Basic)

3.     A custom data class must not be abstract (MustInherit in Visual Basic).

4.     A custom data class must have a public or protected constructor that does not have parameters.

5.     The class cannot implement the IEntityWithChangeTracker or IEntityWithRelationships interfaces because the proxy classes implement these interfaces.

6.     The ProxyCreationEnabled option must be set to true.

7.     Each navigation property must be declared as public, virtual

 

 

Self-Tracking Entities: The EntityObject derived entities, POCO, and POCO proxy entities works well in application where the entity objects can be attached to the object context that handles change tracking on single tier. However, in n-tier application, you have to transfer entities to a tier where the object context is not available e.g. Business tier or presentation tier. So how to track changes and report those changes back to the object context? Answer is “self-tracking entities”. Starting with the .NET Framework version 4, self-tracking entities as its name suggests, can record changes to scalar, complex, and navigation properties on its own. Self-tracking entities do not depend on the Entity Framework so it can be transferred to other tier.

 

Self-Tracking entities have additional change tracking functions and it implements IObjectWithChangeTracker and INotifyPropertyChanged interface. It also mark it as DataContract to be used in WCF services.

 Entity Lifecycle:

we work on CRUD operation (Create, Read, Update, Delete), it’s important to understand entity lifecycle and how it’s being managed by EntityFramework.

 

During entity’s lifetime, each entity has an entity state based on operation performed on it via Context (ObjectContext). The entity state is an enum of type System.Data.EntityState that declares the following values:

1.     Added

2.     Deleted

3.     Modified

4.     Unchanged

5.     Detached

 

The Context not only holds the reference to all the objects retrieved from the database but also it holds the entity states and maintains modifications to the properties of the entity. This feature is known as Change Tracking.

 

The change in entity state from the Unchanged to the Modified state is the only state that’s automatically handled by the context. All other changes must be made explicitly using proper methods of ObjectContext:

 

Sr. 
ObjectContext Methods 
Description 
EntityState 
1
AddObject
Adds an entity to the context
Added
2
Attach
Attaches an entity to the context
Unchanged
3
ApplyCurrentValues
Replace currently attached entity’s scalar value with the property values of detached entity.
Modified
4
ApplyOriginalValues
It applies original database values to attached entity’s properties.
Unchanged
5
DeleteObject
Delete the object from context.
Deleted
6
AcceptAllChanges
pushes the current values of every attached entity into the original values.
Unchanged
7
ChangeState or ChangeObjectState
Change an entity from one state to another without any restrictions (except for Detached)
Based on passed state
8
Detach
Removes an entity from the context.
Detached

 
Code First development with Entity Framework 4.1

Visual Studio 2010 brought new approaches to modeling for Entity Framework 4.1.

1.     Code First

2.     Model First

3.     Database first
 

No comments:

Post a Comment