Getting starded with Entity Framework
Getting started with Entity Framework
Let’s start with what is Entity Framework?
Is a open source ORM (Object Relational Mapping) framework for .NET applications. So developers can work at a higher level of abstraction when working with databases using .NET objects. It deletes the need for most of the data-access code developers usually write.
In the use of data layers developers can also use the repository pattern, unit of work, entity framework all to have a better and scalable database modeling. It fits between business entities and retrieves data and converts it to business entities.
Entity Framework Features
Cross-platform: The Core of the framework can run on Windows, Linux and Mac.
Modelling: Creates EDM (Entity Data Model) based on entities with get/set properties of different data types. It uses this modeling when querying or saving entity data to the database.
Querying: Usage of LINQ queries to retrieve data from underlying database. Database provider translate this LINQ queries to the database SQL. Allows to execute raw SQL queries directly to database
Change tracking: Keeps track of the changes current to instances which need to be submitted
Saving: Executes CRUD, INSERT, UPDATE and DELETE based on changes occurred on the entities
Migrations: EF provides a set of migration commands that can be executed on the CLI or NuGet Package Manager Console
Entity Framework Workflow
In order to create a CRUD first need to follow some steps:
First need to define a model. Defining the domain classes, context class derived from DbContext, and configurations. All the CRUD operations are based on the model.
Second to insert data, adding a domain object to a context and call SaveChanges() method. EF API will build an appropriate INSERT command and execute it to the database.
To read data, execute the LINQ-to-Entities query in your preferred language. EF API will convert this query into SQL query for underlying relational database and execute it.
To edit or delete data, update or remove entity objects from the context call SaveChanges() method. EF API will build the appropriate UPDATE or DELETE command and execute it.
How Entity Framework works?
Entity Framework API (EF6 and EF Core) includes ability to map domain (entity) classes to the database schema, translate and execute LINQ queries to SQL, track changes and save changes to the database
Entity Data Model (EDM)
The first step on EF API is to build an EDM in memory representation of the entire metadata
public class Student
{
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
TableName: Student
StudentId (PK, int, not null)FirstName (nvarchar(50), null)LastName (nvarchar(50), null)
Querying
EF API translate LINQ-to-Entities queries to SQL queries for relational databases using EDM and also converts result back to entity objects.
var context = new SchoolContext();
var students = (from s in context.Students where s.FirstName == “Bill” select s).ToList();
This query translate line to sql to select all the students with the first name of “Bill” and returns a result into a entity object
Saving entities
EF API infers INSERT, UPDATE, and DELETE commands based on the state of each entity as and when an action is performed
context.SaveChanges();
This track the changes create the EDM and execute the INSERT, UPDATE and DELETE command to the database.
Entity Framework Architecture
EDM (Entity Data Model): EDM consist of three main parts Conceptual Model, Storage Model and Mapping
Conceptual Model: Contain the model clases and their relationships.
Storage Model: Is the database design model which includes tables, views, stored procedures, etc.
Mappings: Mapping consist of information about how the conceptual model is mapped to storage model.
Storage Model: Is the database design model which includes tables, views, stored procedures, etc.
LINQ to Entities: Query language used to write queries against the object model. Returns entities, defined on the conceptual mode.
Entity SQL: Query language for (EF6 only) using SQL to retrieve objects.
DbContext
The context class is very important working with EF 6 or Core. Represents ta session with the underlying database to perform the CRUD.
The context class is derived from System.Data.Entity.DbContext using Unit of work and Repository patterns where combine multiple changes.
The context is in charge of query or save data to the database. Configure domain classes, database related mappings, change tracking, caching, etc.
using System.Data.Entity;
public class SchoolContext : DbContext
{
public SchoolContext() {}
// Entities
public DbSet Students { get; set; }
public DbSet StudentAddresses { get; set; }
public DbSet Grades { get; set; }
}
Development Approaches
Database-First
Code-First
Model-First
Database-First
Create the entities for the existing database using EDM wizard integrated in visual Studio or executing EF commands
Tables -> Entity Framework -> Context and Entity Classes
Code-First
Create the entities (domain classes) and context class first then create the database.
Domain Classes -> Entity Framework -> Tables
Model-First
Create the entities, relationships and inheritance on the Visual designer integrated in Visual Studio and generate entities and database.
Visual Designer -> Entity Framework -> Context and Entity Classes - Tablesere...