[go: up one dir, main page]

0% found this document useful (0 votes)
84 views33 pages

Introduction To Entity Framework

This document provides an introduction to entity framework and ORM concepts. It discusses ORM technologies and frameworks, and focuses on the entity framework. It describes the core components of entity framework like DbContext and entity classes. It also explains how to perform basic CRUD operations with entity framework, including reading data with LINQ queries, and creating, updating, and deleting data. The document provides examples of working with entity framework to access and manipulate data in a database.

Uploaded by

zaffar khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views33 pages

Introduction To Entity Framework

This document provides an introduction to entity framework and ORM concepts. It discusses ORM technologies and frameworks, and focuses on the entity framework. It describes the core components of entity framework like DbContext and entity classes. It also explains how to perform basic CRUD operations with entity framework, including reading data with LINQ queries, and creating, updating, and deleting data. The document provides examples of working with entity framework to access and manipulate data in a database.

Uploaded by

zaffar khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Introduction to Entity

framework

ORM Concepts, Entity Framework,


DbContext, CRUD Operations
Table of Contents
1. ORM Technologies – Basic Concepts
2. Entity Framework – Overview
3. Reading Data with EF
4. CRUD operations using Entity Framework
5. Extending Entity Classes

2
Questions

#Entity
3
ORM Technologies
• Object-Relational Mapping (ORM) is a programming technique for
automatic mapping data and schema
• Between relational database tables and object-oriented classes and objects
• ORM creates a "virtual object database"
• Can be used from within the programming language (C# or Java…)
• ORM frameworks automate the ORM process
• A.k.a. Object-Relational Persistence Frameworks

5
ORM Frameworks
• ORM frameworks typically provide the following functionality:
• Creating object model by database schema (DB first model)
• Creating database schema by object model (code first model)
• Querying data by object-oriented API (e.g. LINQ queries)
• Data manipulation operations
• CRUD – create, retrieve, update, delete
• ORM frameworks automatically generate SQL to perform the
requested data operations

6
ORM Advantages and Disadvantages
• Object-relational mapping (ORM) advantages
• Developer productivity: writing less code
• Abstract from differences between object and relational world
• Complexity hidden within the ORM
• Manageability of the CRUD operations for complex relationships
• Easier maintainability
• Disadvantages:
• Reduced performance (due to overhead or incorrect ORM use)
• Reduces flexibility (some operations are hard for implementing)

7
ORM Frameworks in .NET
• Built-in ORM tools in .NET Framework and VS
• Entity Framework (LINQ-to-Entities)
• LINQ-to-SQL (Not used)
• Both combine entity class mappings and code generation, SQL is generated at
runtime
• Third party ORM tools
• Nhibernate
• Telerik OpenAccess ORM

8
Overview of EF
• Entity Framework (EF) is the standard ORM framework for .NET
• Provides a run-time infrastructure for managing SQL-based database data
as .NET objects
• The relational database schema is mapped to an object model
• Visual Studio provides built-in tools for generating Entity Framework data
models
• Data mappings consist of C# classes, XML and attributes
• EF provides a powerful data manipulation API
• CRUD operations and complex querying with LINQ

10
Entity Framework Features
• Maps tables, views, stored procedures and functions as .NET objects
• Provides LINQ-based data queries
• Executed as SQL SELECTs on the database server
• Parameterized queries

• Built-in CRUD operations – Create / Read / Update / Delete


• Creating / deleting / upgrading the database schema
• Tracks changes to in-memory objects

11
Entity Framework Features (2)
• Works with any relational database
• You need an Entity Framework data provider
• Work with a visual model, database or with your own classes
• Has very good default behavior
• Very flexible for more granular control
• Open source – independent release cycle
github.com/aspnet/EntityFramework

12
EF: Basic Workflow
1. Define the data 2. Write & execute 3. EF generates &
model (use a DB query over executes an SQL
Visual designer IQueryable query in the DB
or code first)

13
EF: Basic Workflow (2)
4. EF transforms 5. Modify data 6. Entity Framework
the query with C# code generates &
results into and call "Save executes SQL
.NET objects Changes" command to
modify the DB

14
EF Components
• The DbContext class
• DbContext holds the database connection and the entity classes
• Provides LINQ-based data access
• Implements identity tracking, change tracking, and API for CRUD operations
• Entity classes
• Hold entities (objects with their attributes and relations)
• Each database table is typically mapped to a single C# entity class

15
EF Components (2)
• Associations (relationship mappings)
• An association is a primary key / foreign key-based relationship between two
entity classes
• Allows navigation from one entity to another
var courses = student.Courses.Where(…);
• Concurrency control
• Entity Framework uses optimistic concurrency control
• No locking by default
• Automatic concurrency conflict detection

16
Reading Data with
Entity Framework
The DbContext Class
• The DbContext class is generated by the Visual Studio designer
• DbContext provides:
• Methods for accessing entities (object sets)
• Methods for creating new entities (Add() methods)
• Ability to manipulate database data though entity classes
• Read, modify, delete, insert
• Easily navigate through the table relationships
• Executing LINQ queries as native SQL queries
• Create the DB schema in the database server
18
Using DbContext Class
• var
FirstsoftUniEntities = new SoftUniEntities();
create instance of the DbContext:

• In the constructor you can pass a database connection string and


mapping source
• DbContext properties:
• Connection – the SqlConnection to be used
• CommandTimeout – SQL commands execution timeout in the DB
• All entity classes (tables) are listed as properties
• e.g. IDbSet<Employee> Employees { get; }

19
Reading Data with LINQ Query
• Executing LINQ-to-Entities query over EF entity:

using (var context = new SoftUniEntities())


{ var employees =
from e in context.Employees This will be
where e.JobTitle == "Design Engineer" translated to an
select e; }
• Employees property in the DbContext: SQL query by EF

public partial class SoftUniEntities : DbContext


{
public IDbSet<Employee> Employees { get; set; }
public IDbSet<Project> Projects { get; set; }
public IDbSet<Department> Departments { get; set; }
}
20
Reading Data with LINQ Query
• We can also use extension methods for constructing the query

using (var context = new SoftUniEntities())


{
var employees = context.Employees
.Where(c => c.JobTitle == "Design Engineering")
.Select(c => c.FirstName)
.ToList(); This is called projection
• Find element
} by id
ToList() method
executes the query
using (var context = new SoftUniEntities())
{
var project = context.Projects.Find(2);
Console.WriteLine(project.Name);
} 21
Logging the Native SQL Queries

•var
Printing
querythe=native database SQL command behind a query:
context.Employees;
Console.WriteLine(query.ToString());

• This will print the SQL native query executed at the database server to
select all Employees
• Can be printed to file using StreamWriter class instead of Console class

22
with EF
Creating New Data
• To create a new database row use the method Add(…) of the
corresponding
var project = collection:
new Project()
Create a new
{ project object
Name = "Judge System",
StartDate = new DateTime(2015, 4, 15),
};

context.Projects.Add(project);
context.SaveChanges(); Mark the object for inserting

This will execute an SQL INSERT


• SaveChanges() method executes the SQL insert / update / delete
commands in the database
24
Cascading Inserts
• We can also
Employee add cascading
employee entities to the database:
= new Employee();
employee.FirstName = "Petya";
employee.LastName = "Grozdarska";
employee.Projects.Add(new Project { Name = "SoftUni Conf"} );
softUniEntities.Employees.Add(employee);
softUniEntities.SaveChanges();

• This way we don't have to add Project individually


• They will be added when the Employee entity (employee) is inserted to the
database

25
Updating Existing Data
• DbContext allows modifying entity properties and persisting them in
the database
• Just load an entity, modify it and call SaveChanges()

• The DbContext automatically tracks all changes made on its entity


objects
Employees employee =
This will execute an SQL
softUniEntities.Employees.First();
SELECT to load the first
employees.FirstName = "Alex";
order
context.SaveChanges(); This will execute an
SQL UPDATE
26
Deleting Existing Data
• Delete is done by Remove() on the specified entity collection
• SaveChanges() method performs the delete action in the database

Employees employee = Mark the entity for


softUniEntities.Employees.First(); deleting at the next save

softUniEntities.Employees.Remove(employee);
softUniEntities.SaveChanges(); This will execute the
SQL DELETE command

27
Extending Entity Classes

Add Methods like ToString(), Equals(), etc…


Extending Entity Classes
• When using "database first" or "model first" entity classes are
separate .cs files, generated by T4 template XXXModel.tt
• Each time we update the EntitiesModel from the database all files are
generated anew
• If we add methods like ToString(), they will be lost
• Entity classes are "partial"  extend them in another file
• When using "code first" this is not a problem

29
Summary
• ORM frameworks maps database schema to
objects in a programming language
• Facilitates development process
• Entity Framework is the standard ORM for C#
• Can work with any database if there is provider
• Supports CRUD operations with DbContext
• Provides LINQ-based data queries
• Translated to SQL at runtime
• Automatically tracks changes to in-memory objects

30
Introduction to Entity Framework

? ?
?

stio ns ? ?

Qu e ?
?

?
https://softuni.bg/courses/
License
• This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International" license

• Attribution: this work may contain portions from


• "Databases" course by Telerik Academy under CC-BY-NC-SA license

32
Free Trainings @ Software University
• Software University Foundation – softuni.org
• Software University – High-Quality Education,
Profession and Job for Software Developers
• softuni.bg
• Software University @ Facebook
• facebook.com/SoftwareUniversity
• Software University @ YouTube
• youtube.com/SoftwareUniversity
• Software University Forums – forum.softuni.bg

You might also like