Friday, January 20, 2017

EF Architecture and Fundamentals

ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework which:
  • Enable developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write, OR simply Is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database, and for working with the results in addition to DataReader and DataSet
  • Provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals
  • Is a tool for storing data from domain objects to relational database like MS SQL Server, in an automated way without much programming
  • Allows us to keep our database design separate from our domain class design. This makes the application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so that the developer doesn't need to write it manually
  • Includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects map to relational database objects (tables, views & stored procedures)

Architecture

EDM (Entity Data Model):consists of below three parts:
  • 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 consist information about how the conceptual model is mapped to 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 also the developer will need 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 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 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 database.

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


Types of Entities: There were four types of Entities in Entity Framework 4.x, but from 5.0 is limited to POCO and POCO Proxy entities.
  • EntityObject
  • POCO (Plain Old CLR Object): It is like any other normal .net class. These support most of the same query, insert, update, and delete behaviors as entity types that are generated by the Entity Data Model
  • POCO Proxy (dynamic proxy): Dynamic Proxy is a runtime proxy class of POCO entity. POCO entity becomes POCO Proxy entity if it meets certain requirements in order to enable lazy loading and automatic change tracking. It adds some methods at runtime to your POCO class which does instant change tracking and lazy loading stuff
  • Self-Tracking Entities

POCO entity should meet the following requirements to become a POCO proxy:
  • A custom data class must be declared with public access.
  • A custom data class must not be sealed (NotInheritable in Visual Basic)
  • A custom data class must not be abstract (MustInherit in Visual Basic).
  • ProxyCreationEnabled option should not set to false (default is true) in context class
  • Each navigation property must be declared as public, virtual

By default dynamic proxy is enabled for every entity. However, you can disable dynamic proxy by setting the ProxyCreationEnabled option to false in context class. context.Configuration.ProxyCreationEnabled = false;

EDM generates POCO entities which satisfy the above requirements for a dynamic proxy by default. You can use ObjectContext.GetObjectType() to find the actual type of dynamic proxy.


Entity Properties
  • Scalar properties: Scalar properties are properties whose actual values are contained in the entity. For example, Student entity has scalar properties e.g. StudentId, StudentName. These correspond with the Student table columns.
  • Navigation properties: Navigation properties are pointers to other related entities. The Student has Standard property as a navigation property that will enable application to navigate from a Student to related Standard entity.

Querying with EDM

You can query EDM mainly in three ways: LINQ to Entities, Entity SQL, and Native SQL

LINQ to Entities: L2E query syntax is easier to learn than Entity SQL. You can use your LINQ skills for querying with EDM. These are LINQ Method Syntax with Lamda expression OR by LINQ query syntax itself, examples as below:

LINQ Method Syntax:
using (var context = new SchoolDBEntities())
{
var L2EQuery = context.Students.where(s => s.StudentName == “Bill”);
}
LINQ Query Syntax:
using (var context = new SchoolDBEntities())
{
var L2EQuery = (from st in context.Students
where st.StudentName == "Bill"
select st);
}
Entity SQL: Entity SQL is another way to create a query. It is processed by the Entity Framework’s Object Services directly. It returns ObjectQuery instead of IQueryable. You need ObjectContext to create a query using Entity SQL. The following code snippet shows the same query result as L2E query above:
string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students AS st WHERE st.StudentName == 'Bill'";

var objctx = (ctx as IObjectContextAdapter).ObjectContext;

ObjectQuery student = objctx.CreateQuery(sqlString);
Student newStudent = student.First();

You can also use EntityConnection and EntityCommand to execute Entity SQL as shown below:

using (var con = new EntityConnection("name=SchoolDBEntities"))
{
con.Open();
EntityCommand cmd = con.CreateCommand();

cmd.CommandText = "SELECT VALUE st FROM SchoolDBEntities.Students as st where st.StudentName='Bill'";
Dictionary dict = new Dictionary();

using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
int a = rdr.GetInt32(0);
var b = rdr.GetString(1);
dict.Add(a, b);
}
}
}
Native SQL: You can execute native SQL queries for a relational database as shown below:
using (var ctx = new SchoolDBEntities())
{
var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student
               where studentname='Bill'").FirstOrDefault();
}
With this I am concluding this article. Feel free to share your feedback.

Happy Programming !!!

No comments:

Post a Comment