Knowledge Management Banner

Knowledge Management Banner

Entity Framework

What is Entity Framework ?

It is an ORM framework. Object relational mapping is a framework that generate classes
based on database tables and vice – versa.

Entity Framework Architecture

EDM (Entity Data Model) :

EDM consists of three main parts - Conceptual model, Mapping and Storage model.

Conceptual Model :

The conceptual model contains the model classes and their relationships. This will be independent
from your database table design.

Storage Model :

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

Mapping :

Mapping consists of information about how the conceptual model is mapped to the storage
model.

LINQ to Entities :

LINQ to Entities is a 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 another query language just like LINQ to Entities. However, it is a little more difficult
than L2E and the developer will have to learn it separately.

Object Service :

Object service is a main entry point for accessing data from the database and to return it back.
Object service is responsible for materialization, which is the process of converting data returned
from an 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 a SQL query which
is understood by the underlying database. It communicates with the ADO.Net data provider which
in turn sends or retrieves data from the database.

ADO.Net Data Provider :

This layer communicates with the database using standard ADO.Net.

--------------------------------------------------------------------------------------------------------------------------

What is Entity ?

Entity is an object in the system that we want to model or store information in.

Types Of Entity

POCO Entity (Plain Old CLR Object) :
  • POCO class is the class that doesn't depend on any framework specific base class. 
  • It is like any other normal .net class which is why it is called "Plain Old CLR Objects".
Example

 public class Student  
 {  
 public Student()  
 {  
 this.Courses = new List<Course>();  
 }  
 public int StudentID { get; set; }  
 public string StudentName { get; set; }  
 public Nullable<int> StandardId { get; set; }  
 public Standard Standard { get; set; }  
 public StudentAddress StudentAddress { get; set; }  
 public IList<Course> Courses { get; set; }  
 }  

Dynamic Proxy (POCO Proxy) :
  • Dynamic Proxy is a runtime proxy class of POCO entity. It is like a wrapper class of POCO entity. Dynamic proxy entities allow lazy loading and automatic change tracking.
Example

 public class Student  
 {  
 public Student()  
 {  
 this.Courses = new HashSet<Course>();  
 }  
 public int StudentID { get; set; }  
 public string StudentName { get; set; }  
 public Nullable<int> StandardId { get; set; }  
 public virtual Standard Standard { get; set; }  
 public virtual StudentAddress StudentAddress { get; set; }  
 public virtual ICollection<Course> Courses { get; set; }  
 }  

POCO entity should meet the following requirements to become a POCO proxy:

  • A POCO class must be declared with public access.
  • A POCO class must not be sealed (NotInheritable in Visual Basic)
  • A POCO class must not be abstract (MustInherit in Visual Basic).
  • Each navigation property must be declared as public, virtual
  • Each collection property must be ICollection<T>
  • ProxyCreationEnabled option must NOT be false (default is true) in context class

Entity RelationShips

One to one relation ship

  • Student and StudentAddress have a One-to-One relationship.A student can have only
  • one or zero address.
  • StudentAddress entity has StudentId property as PrimaryKey which makes it a
  • One-to-One relationship.
  • In edmx designer it is marked as 1 to 1

One-to-Many Relationship :

  • The Standard and Teacher entities have a One-to-Many relationship. The standardId
  • is Primary key. Teacher entity will contain StandardId as foreign key which will not be
  • unique. This makes its one to many relation ship.
  • In edmx designer it is marked as 1 to *

Many-to-Many Relationship :

  • Student and Course have Many-to-Many relationships.
  • Student entity will have Id as Primary key, and will have CourseId as foreign key for
  • Course but will not be a primary key.
  • Similarly Course will have Id as primary key, and have StudentId as foreign key for
  • Student but will not be primary key.
  • In edmx designer it is marked as * to *

ADO.NET (Activex Data object)
  • It is a program that is used to access data from database. It is part of base class library that is used in Microsoft .net framework.
What is .NET ?
  • It is an environment created by microsoft,

Approaches of entity framework ?

Schema first approach

  • Create database first
  • Add entity data model by connecting to database.

Model first approach

  • Add blank entity data model and create entities in designer
  • Generate database from model

Code first approach

  • Create classes which represent database table
  • Define DbContext class where the classes are to be converted to database.
  • Add connection string in web.config
  • Add the data source & define data method

Eager Loading

What is Eager loading ?
  • Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved using the Include() method.
  • example
  •  var res = (from s in context.Students.Include("Standard")  
              where s.StudentName == "Student1"  
              select s).FirstOrDefault();  
When to Use Eager Loading ?
  • In "one side" of one-to-many relations that you sure are used every where with main entity.

Lazy Loading

What is Lazy Loading ?
  • Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Lazy loading is by default in Entity Framework means delaying the loading of related data.
  •  using (var ctxDb = new SomeCtx())  
     {  
       ctxDb.Configuration.LazyLoadingEnabled = false;  
       var result = from s in ctxDb.Students.Include("Address")  
                    select s;  
       result = result.OrderByDescending(m => m.id).ThenBy(s => s.Name);  
       return result.ToList();  
     }  
    

Explicit Loading
  • Even with lazy loading disabled, it is still possible to lazily load related entities, but it must be done with an explicit call. Use the Load method of DBEntityEntry object to accomplish this.
  • Example
  •  using (var context = new SchoolDBEntities())  
     {  
     //Disable Lazy loading  
     context.Configuration.LazyLoadingEnabled = false;  
     var student = (from s in context.Students  
     where s.StudentName == "Bill"  
     select s).FirstOrDefault<Student>();  
     context.Entry(student).Reference(s => s.Standard).Load();  
     }  
    

Concurrency in Entity Framework

  • EF saves the entity to the database, assuming that the same data has not changed since the entity was loaded. If it determines that the data has changed, then an exception is thrown and you must resolve the conflict before attempting to save it again.
  • First of all, you need to have a rowversion column in the table in order to handle concurrency with entity. Rowversion is a datatype in the SQL Server that automatically generates unique binary number whenever the insert or update operation is performed in a table. The rowversion datatype is simply an incrementing number. Rowversion is a similar to the timestamp datatype.
  • Then, you need to set the concurrency mode to fixed by right clicking on RowVersion property in the entity (right click on RowVersion property not entity) -> select Property. Change Concurrency Mode to Fixed from None in the property window as shown below:


How to choose development approach in Entity Framework ?











No comments

Powered by Blogger.